Today, when creating an application, you need to use a method similar to pressing the return key of QQ and not destroying the Activity (that is, do not call the Activity. finish (), the system does not call onDestroy), but is similar to pressing the Home Key to make the Activity similar to "paused" (that is, only onPause and onDestroy are called ).
I first thought of the Override onKeyDown method. However, after debugging, I found that when the Home key is pressed, the system will not send messages to this system for processing. That is to say, simulating KEYCODE_HOME is ineffective, then I found the dispatchKeyEvent function on the Internet. The following is a description of the function:
Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that shocould be handled normally.
However, the message generated by the Home button does not pass through this process. It seems that the message generated by the Home button is processed by the system. So I thought of starting from other aspects and finally found the following methods:
@ Overridepublic boolean onKeyDown (int keyCode, KeyEvent event) {// TODO Auto-generated method stubif (keyCode = KeyEvent. KEYCODE_BACK) {Intent intent = new Intent (Intent. ACTION_MAIN); intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); // pay attention to intent. addCategory (Intent. CATEGORY_HOME); this. startActivity (intent); return true;} return super. onKeyDown (keyCode, event );}
Pay special attention to intent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); this sentence must be added because the launchMode of the Activity is executed in standard by default, if this tag is not added, a new Activity is created and placed in the same Task as the current Activity. The following describes FLAG_ACTIVITY_NEW_TASK.
FLAG_ACTIVITY_NEW_TASKMark
When the Intent object passed to startActivity () contains the FLAG_ACTIVITY_NEW_TASK tag, the system searches for different tasks for the activity to be started. If the affinity attribute of the activity to be started is different from that of all current tasks, the system creates a new task with the affinity attribute, and press the activity to be started into the new task stack; otherwise, press the activity into the stack with the same affinity attribute.
For more information about Affinities and tasks, see (reproduced) Affinities and tasks in Android