Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onBackPressed/onUserLeaveHint

Tags:

android

Just a bit of advice needed really. I have an Activity running with my game in it and when the user presses the Back button it will exit back to the Main Menu using the onBackPressed() method, but I am also overriding the onUserLeaveHint() to do the same action if the Home Button is pressed or a phone call is received. However this method is also called when the Back button is pressed, meaning that the Main Menu Intent is called twice with one on top of the other.

If anyone has an idea about how to get around this issue or a better way of handling the two events it would be much appreciated.

Thanks.

like image 297
Nick Avatar asked Jul 07 '11 14:07

Nick


People also ask

What is onUserLeaveHint?

onUserLeaveHint() is a protected method as other lifecycle methods of the activity and if you are handling onUserLeaveHint this will take care of the following case. When User hits home key. When User hits back key.

What is Android activity Creator?

An ActivityCreator is the first step towards the creation of a new Android project. It is made up of a shell script that will be used to create new file system structure necessary for writing codes within the Android IDE.

Can we create activity without UI in Android?

Explanation. Generally, every activity is having its UI(Layout). But if a developer wants to create an activity without UI, he can do it.

What does finish () do in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.


2 Answers

onUserLeaveHint() is a protected method as other lifecycle methods of the activity and if you are handling onUserLeaveHint this will take care of the following case

  1. When User hits home key
  2. When User hits back key
  3. When User hits annunciator bar

Basically it hints about the user is trying to leave your activity. That means if you are handling onUserLeaveHint() you don’t need to handle onBackPressed() in your code.

like image 155
AndyW Avatar answered Oct 03 '22 12:10

AndyW


Just an idea that might help you, i'm using it for my "home-made" ActionBar to determine when the user has actually arrived at the main (and last) activity before exiting. I start the Main-Activity manually and clear the whole activity stack by setting the FLAG_ACTIVITY_CLEAR_TOP flag, so if the user now hits the back button once again, the app is gonna get closed.

Intent intent = new Intent(getContext(), MainMenu.class).
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
like image 29
iDroid Avatar answered Oct 03 '22 12:10

iDroid