01 | private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() { |
02 | final String SYSTEM_DIALOG_REASON_KEY = "reason" ; |
03 | final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey" ; |
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)) { |
然后在onreate()方法中,注册
1 | final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); |
2 | registerReceiver(homePressReceiver, homeFilter); |
当然最后为了程序的严谨性也是为了防止出错,我们在onDestory()方法中,也要解除注册
1 | if (homePressReceiver != null ){ |
3 | unregisterReceiver(homePressReceiver); |
4 | } catch (Exception e) { |
5 | Log.e(TAG, "unregisterReceiver homePressReceiver failure :" +e.getCause()); |
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() { |
05 | public void onReceive( final Context context, final Intent intent) { |
06 | final String action = intent.getAction(); |
07 | if (Intent.ACTION_SCREEN_OFF.equals(action)) { |
13 | IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); |
14 | registerReceiver(mBatInfoReceiver, filter); |
16 | if (mBatInfoReceiver != null ){ |
18 | unregisterReceiver(mBatInfoReceiver); |
19 | } catch (Exception e) { |
20 | Log.e(TAG, "unregisterReceiver mBatInfoReceiver failure :" +e.getCause()); |