Problem description:
Since Android 4.0 and later, developers cannot listen to or block the Home key. For KEYCODE_HOME, the official description is as follows:
Therefore, you cannot directly listen to the Home key unless you modify the Framework. Some friends on the Internet say that they are listening to the Log, but currently pressing the Home key does not display the Log, in addition, different phone models will not be the same even if displayed.
I have found a lot of solutions on the Internet ...... Helpless.
To enable users to process events after pressing the Home key, the following solution is used.
Solution:
1. Ideas
Activity lifecycle,
Each Activity must follow the OnResume () method when it is started, and every Activity must follow the OnStop method when it is ended, after you press the Home key, the Activity also needs to execute the Onstop () method (as shown in the figure, when the Activity is invisible ).
Therefore, we can judge the status of all the activities in the OnStop () method of each Activity. If all the activities are invisible (OnStop () is executed ()), perform the operations we want to perform.
2. Logic
Custom Application: defines a global HashMap and two methods. method 1 addActivityStatus (Activity activity) is used to manage the Activity status. method 2 isAllActivityAlive () used to query whether all the activities are active.
In the OnResume () method of each Activity, call addActivityStatus (Activity activity) to set the status of the current Activity to true. In the OnStop () method, call addActivityStatus (Activity activity) first) set the status to false and call isAllActivityAlive () to check whether all the activities are in the inactive status, if all activities are not activated (all activities have been OnStop (), perform the operation you Want to do !!!
It's messy...
3. Implementation
1. Custom Application
ManageApplication HashMap <String, Boolean> mapActivity = HashMap <String, Boolean> (); ManageApplication application = addActivityStatus (Activity activity,} res = Iterator iter = Map. entry entry = Object key = value =}View Code
2. Set the Application to a custom Application in Mainfest.
3. perform the following operations in each Activity:
3.1 getApplication in OnCreat ()
setContentView(R.layout.activity_main); Log.e("Status", "OnCreate"
3.2 rewrite OnResume () and add the current Activity status to true.
"Status", "onResume",
3.3 override OnStop (), change the current Activity status to false, and check whether all the activities are in the inactive status.
"Status", "onStop", alived ="All Activity Status", alived + ""(!
OK !!! Success! O (partition _ partition) o