Reprint please indicate source: http://blog.csdn.net/kjunchen/article/details/50429694
Android App Development Press the back button to rewind to background execution
We use a lot of Android applications (such as QQ, Weibo), in the main interface of the application press the Back button, the application does not exit, but into the background to execute.
So, how is it implemented in development? I found two ways to do this:
First, the Monitoring return key
1. Rewrite the onbackpressed () method in the activity.
@OverridepublicvoidonBackPressed() { //此处写退向后台的处理}
2. Rewrite the onkeydown () method (some application hints click the Back button again to exit the app is the article done here).
@OverridepublicbooleanonKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) {//假设返回键按下 //此处写退向后台的处理 returntrue; } returnsuper.onKeyDown(keyCode, event);}
Second, back to the background to execute
1, just need a word to fix, call Movetasktoback () method, this method needs to set a Boolean parameter. Ture Press the return key in whatever activity to exit and go into the background. False simply press the return key in the root activity to go back to the background execution.
moveTaskToBack(false);
2, use intent. Return to the main phone screen.
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 specific.
@OverridepublicvoidonBackPressed() { //方式一:将此任务转向后台 moveTaskToBack(false); //方式二:返回手机的主屏幕 /*Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent);*/
Welcome to add QQ Group Exchange:365532949
Android App Development Press the back button to rewind to background execution