01
privatefinalBroadcastReceiverhomePressReceiver=newBroadcastReceiver(){
02
finalStringSYSTEM_DIALOG_REASON_KEY="reason";
03
finalStringSYSTEM_DIALOG_REASON_HOME_KEY="homekey";
04
@Override
05
publicvoidonReceive(Contextcontext,Intentintent){
06
Stringaction=intent.getAction();
07
if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
08
Stringreason=intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
09
if(reason!=null&&reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)){
10
//自己随意控制程序,关闭...
11
}
12
}
13
}
14
};
然后在onreate()方法中,注册
1
finalIntentFilterhomeFilter=newIntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
2
registerReceiver(homePressReceiver,homeFilter);
当然最后为了程序的严谨性也是为了防止出错,我们在onDestory()方法中,也要解除注册
1
if(homePressReceiver!=null){
2
try{
3
unregisterReceiver(homePressReceiver);
4
}catch(Exceptione){
5
Log.e(TAG,"unregisterReceiverhomePressReceiverfailure:"+e.getCause());
6
}
7
}
2,电源监听,先要有权限
1
<uses-permissionandroid:name="android.permission.WAKE_LOCK"/>
然后监听两个action
01
Intent.ACTION_SCREEN_OFF
02
Intent.ACTION_SCREEN_ON
03
privatefinalBroadcastReceivermBatInfoReceiver=newBroadcastReceiver(){
04
@Override
05
publicvoidonReceive(finalContextcontext,finalIntentintent){
06
finalStringaction=intent.getAction();
07
if(Intent.ACTION_SCREEN_OFF.equals(action)){
08
//退出程序...
09
}
10
}
11
};
12
onCreate()方法中注册
13
IntentFilterfilter=newIntentFilter(Intent.ACTION_SCREEN_OFF);
14
registerReceiver(mBatInfoReceiver,filter);
15
onDestory()方法中解除注册
16
if(mBatInfoReceiver!=null){
17
try{
18
unregisterReceiver(mBatInfoReceiver);
19
}catch(Exceptione){
20
Log.e(TAG,"unregisterReceivermBatInfoReceiverfailure:"+e.getCause());
21
}
22
}