android程序监听home键与电源键
jopen
11年前
private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() { final String SYSTEM_DIALOG_REASON_KEY = "reason"; final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { //自己随意控制程序,关闭... } } } };
然后在onreate()方法中,注册
final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(homePressReceiver, homeFilter);
当然最后为了程序的严谨性也是为了防止出错,我们在onDestory()方法中,也要解除注册
if(homePressReceiver != null){ try { unregisterReceiver(homePressReceiver); } catch (Exception e) { Log.e(TAG, "unregisterReceiver homePressReceiver failure :"+e.getCause()); } }
2,电源监听,先要有权限
<uses-permission android:name="android.permission.WAKE_LOCK" />
然后监听两个action
Intent.ACTION_SCREEN_OFF Intent.ACTION_SCREEN_ON private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (Intent.ACTION_SCREEN_OFF.equals(action)) { //退出程序... } } }; onCreate()方法中注册 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); registerReceiver(mBatInfoReceiver, filter); onDestory()方法中解除注册 if(mBatInfoReceiver != null){ try { unregisterReceiver(mBatInfoReceiver); } catch (Exception e) { Log.e(TAG, "unregisterReceiver mBatInfoReceiver failure :"+e.getCause()); } }