Android - How to exit an app when user press the home button?

一笑奈何 提交于 2019-12-19 04:08:27

问题


I want to know how to exit an app when user press the Home Button.

As far as i know that Home Button moves the running app in background and puts Launcher process in front.

I know i can use finish() but i don't know where i should call it because i have no idea which function is going to get a call when user will press the Home Key.

Thanks.


回答1:


Depending on what you want to do, overriding onUserLeaveHint might be the best bet:

http://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()

This will let your app know that your app is being exited because the user chose to switch apps (Like by hitting the Home button or selecting a notification). This hint function will not be called if an incoming phone call (or similar) is causing your app to go to the background, as the user didn't initiate that action.




回答2:


In my case,

I have many activities in application so if I use 'onUserLeaveHint', 'onStop' or ...

It just catch activity transition.

So I put below code every activities. And finally catch user's home button action.

first, you have singleton object

public class ActivityContext {
    public static Context context = null;
}

and every activities,

@Override
protected void onStop(){  //onStop runs after New one's onResume
    super.onStop();
    if(ActivityContext.context==context) { //user home button out
        AppStartEnd.sendAppEndData(context);
    }
}
@Override
protected void onResume(){  
    super.onResume();
    ActivityContext.context = YourActivity.this;
}

I hope this will help you



来源:https://stackoverflow.com/questions/5842272/android-how-to-exit-an-app-when-user-press-the-home-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!