Thursday, May 29, 2014

Unity Android back button problem

In my unity 4.3.4f1, the back button seems doesn't work. Sometimes, we want to make back button goes to the home screen or menu without exiting the application. There is a way to do this by simply calling android native code.

At first, we can use Input.GetKeyDown(KeyCode.Escape) to detect the back button input. I wrote the code inside update function:

// We also can write it in FixedUpdate function or whatever . The point is we want to check if the user press the back button
void Update()
{
   if (Input.GetKeyDown(KeyCode.Escape)) 
   { 
      // Do your code here . . .

   }
}



Now we want to execute what happens if user press the back button. Here is the common situation:
1. Quit the application
2. Go back to menu screen

1. Quit the application

This is pretty straight forward. We can simply call Application.Quit();

2. Go back to menu screen

This is common if you want to build game for android. You can call the android native code to do this. Add a macro to make sure you run it in android.

// Inside "Do your code here . . ."
#if UNITY_ANDROID
   // Get the unity player activity
   AndroidJavaObject activity = 
      new AndroidJavaClass("com.unity3d.player.UnityPlayer")
      .GetStatic<AndroidJavaObject>("currentActivity");

   // call activity's boolean moveTaskToBack(boolean nonRoot) function
   activity.Call<bool>("moveTaskToBack"true);

#endif

activity.Call<bool>("moveTaskToBack", true); The method signature is it takes parameter boolean and it returns boolean. So our call function signature must match the moveTaskToBack signature.

5 comments:

  1. Holy crap thank you! I've been searching for this all over and there were no good answers and my attempt to alter Unity's activity class failed. Thank you so much!! Unit needs to build this in as a standard function!

    ReplyDelete
  2. this kinda works BUT the app opens and closes immediately after i restart it from the home screen in android.

    ReplyDelete
  3. Can I just pay someone to do this for me I can't work this out. I notice now though even Google maps has to run in a minimised window. Someone help. I'll pay.. ivelindustries@hotmail.com

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete