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