Relation between “Run in background” setting and OnApplicationPause method

Relation between “Run in background” setting and OnApplicationPause method

I'm working on a game for mobile platforms (Android at the moment, in the future it should be available for iOS and WinPhone) and I want to trigger a certain method when the game is un-paused. For this I'm trying to use OnApplicationPause(bool paused) method (when the "paused" variable is false), but the process is not working as expected. These are my questions:

In the player settings, does the "Run in background" setting influence the build (since this setting can be found only in Web player/Desktop build tabs, and I'm creating an Android build).
The problem that we started to experience is that when the game is paused, it crashes and the player has to restart the game. Is this connected to the "Run in background" setting?
What is the relation between "Run in background" and OnApplicationPause - will the OnApplicationPause be called if the "Run in background" is checked?
What is the difference between OnApplicationPause and OnApplicationFocus (meaning, which actions change the focus and which will pause the game)?

The code that I'm trying to execute at the moment is fairly simple:
void OnApplicationPause(bool paused)
{
  if(!paused) AddCoins( x => PlayerPrefs.SetInt("CoinCount", PlayerPrefs.GetInt("CoinCount")+x));
}

The idea of this code is to add a certain number of coins if the player watches an advert (the number of coins is calculated by the ad provider).
Thanks in advance

Solutions/Answers:

Answer 1:

OnApplicationPause(bool state) is called when the user pauses and unpauses the game, normally by hitting the Pause button found in your game (which you need to implement the functionality for – by setting Time.timeScale = 0).

Sometimes it’s called when the application is put in (or comes back from) the background too (user hits Home button for example). But this behavior differs on each platform and you cannot safely rely on it.

OnApplicationFocus(bool state) is called when the app goes into (or comes from) background, usually because the user hits the Home button, and/or switches to another application. This behavior should be consistent on all the platforms.

In order to be safe I believe it’s best to implement both functions.

  • If the state is false (the application goes into the background) you should pause the game – Time.timeScale = 0
  • If the state is true (the application comes back to foreground) you should unpause the game – Time.timeScale = 1

References