Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Suspend / Pause application on mobile

Discussion in 'Scripting' started by supdawg, Mar 13, 2015.

  1. supdawg

    supdawg

    Joined:
    Jul 8, 2012
    Posts:
    11
    There must be threads asking this already but I cannot find any as google is packed full of 1000s of unrelated threads with the same keywords.

    Pressing Home is obviously the best way to exit a game on a mobile platform, but I want an exit button, and Im pretty sure most other users will too, it just feels incomplete without one.

    However I want the OS to be able to do its job effectively and suspend the game until such time as it is required again or closed to reclaim resources.

    Therefore I want to suspend, not quit, the application from code. To give the user the fuzzy glow that comes from pressing Exit, without depriving the OS of its god given right to do what it wants with your stuff. I want to both have the cake, and eat the cake.

    How do I suspend the application from code?
     
  2. bigdaddy

    bigdaddy

    Joined:
    May 24, 2011
    Posts:
    153
    Just realize that having an Exit button will most likely cause Apple to reject your app on iOS
     
  3. supdawg

    supdawg

    Joined:
    Jul 8, 2012
    Posts:
    11
    Even if it doesn't actually exit? It would just be calling the same thing as the home button.
     
  4. supdawg

    supdawg

    Joined:
    Jul 8, 2012
    Posts:
    11
    I just noticed this is a loose end in my comment history. The answer for posterity is...
    Code (csharp):
    1. #if UNITY_ANDROID
    2. // Get the unity player activity
    3. AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
    4. // call activity's boolean moveTaskToBack(boolean nonRoot) function
    5. // documentation: http://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)
    6. activity.Call<bool>("moveTaskToBack", true);   //To suspend
    7. //activity.Call<void>("Finish",true);   //To End
    8. #endif
     
    AxPetre likes this.