1

I have developed an unity android application. I want to perform some action when app is in foreground and also in background. Right now i am trying to print log in several interval of time in recursive manner. I am using this method to call my countdown timer.

void OnApplicationFocus(bool hasFocus){
        StartBattle();
        isPaused = !hasFocus;
        Debug.Log("isPaused " + isPaused);
    }

void OnApplicationPause(bool pauseStatus){
      isPaused = pauseStatus;
      StartBattle();
     }

And this method to print data in a recursive manner.

public void StartBattle(){
        StartCoroutine(BattleRecursive(0));
    }

public IEnumerator BattleRecursive(int depth){
        // Start Coroutine"

        yield return new WaitForSeconds(2f);

        if (depth == 0)
            yield return StartCoroutine(BattleRecursive(depth + 1));

        if (depth == 1)
            yield return StartCoroutine(BattleRecursive(depth + 1));

        Debug.Log("MyCoroutine is now finished at depth " + depth);
    }

Log is printing very well when app is in foreground, But when app is in background, it is not printing anything.

Programmer
  • 121,791
  • 22
  • 236
  • 328

1 Answers1

2

You can't execute your Unity C# code in the background when Unity exit. This code you want to run in the background must be made in Java.

Write the code you want to Execute in Java not in C# then use Android's Intent to start a service. This requires that you send current Unity's Context or Activity to your plugin in order to start the service. You can find examples on how to do that here and here.

Programmer
  • 121,791
  • 22
  • 236
  • 328