Android App Development Press the back button to run back to the background
Many of our daily use of Android applications (such as QQ, Weibo), in the main interface of the application press the Back button, the app does not exit, but into the background to run.
So, how is it implemented in development? I found two ways to do this:
First, monitoring the return key
1. Rewrite the onbackpressed () method in the activity.
@Overridepublic void onBackPressed() { //此处写退向后台的处理}
2. Rewrite the onkeydown () method (some application hints click the Back button again to exit the app is the article done here).
@Override Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {if(keycode = = Keyevent.keycode_back) {//If the return key is pressed //write back to background processing here return true; }return Super. OnKeyDown (KeyCode, event);}
Second, back to the background to run
1, just a word to fix, call Movetasktoback () method, this method needs to set a Boolean parameter, ture in any activity press the return key to exit and run into the background, false Only the return key is pressed in the root activity to run back to the background.
moveTaskToBack(false);
2. Use intent to return to the main screen of the phone.
Intent Intent = new Intent (Intent. ACTION_main);Intent. SetFlags(Intent. FLAG_activity_new_task);Intent. Addcategory(Intent. CATEGORY_home);StartActivity (Intent);
Finally, a little more detail.
@Override Public void onbackpressed() {//Mode one: Turn this task back to the backgroundMovetasktoback (false);//Mode two: Return to the phone's home screen /*intent Intent = new Intent (intent.action_main); Intent.setflags (Intent.flag_activity_new_task); Intent.addcategory (Intent.category_home); StartActivity (Intent); * *}
Android App Press Back button to run back to background