android程序监听home键与电源键

01 private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() {
02 final String SYSTEM_DIALOG_REASON_KEY = "reason";
03 final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
04 @Override
05 public void onReceive(Context context, Intent intent) {
06 String action = intent.getAction();
07 if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
08 String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
09 if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
10 //自己随意控制程序,关闭...
11 }
12 }
13 }
14 };

然后在onreate()方法中,注册

1 final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
2 registerReceiver(homePressReceiver, homeFilter);

当然最后为了程序的严谨性也是为了防止出错,我们在onDestory()方法中,也要解除注册

1 if(homePressReceiver != null){
2 try {
3 unregisterReceiver(homePressReceiver);
4 catch (Exception e) {
5 Log.e(TAG, "unregisterReceiver homePressReceiver failure :"+e.getCause());
6 }
7 }

2,电源监听,先要有权限

1 <uses-permission android:name="android.permission.WAKE_LOCK" />

然后监听两个action

01 Intent.ACTION_SCREEN_OFF
02 Intent.ACTION_SCREEN_ON
03 private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
04 @Override
05 public void onReceive(final Context context, final Intent intent) {
06 final String action = intent.getAction();
07 if (Intent.ACTION_SCREEN_OFF.equals(action)) {
08 //退出程序...
09 }
10 }
11 };
12 onCreate()方法中注册
13 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
14 registerReceiver(mBatInfoReceiver, filter);
15 onDestory()方法中解除注册
16 if(mBatInfoReceiver != null){
17 try {
18 unregisterReceiver(mBatInfoReceiver);
19 catch (Exception e) {
20 Log.e(TAG, "unregisterReceiver mBatInfoReceiver failure :"+e.getCause());
21 }
22 }
posted @ 2014-03-20 10:12  xiaochao1234  阅读(1399)  评论(0编辑  收藏  举报