Home键监听
编写广播接收器 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)) {
// 自己随意控制程序,关闭...
}
}
}
在onCreate中注册接收器
final IntentFilter homeFilter = new IntentFilter(
Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(homePressReceiver, homeFilter);
在onDestory()中解除注册防止报错
if(homePressReceiver != null) {
try {
unregisterReceiver(homePressReceiver);
}
catch(Exception e) {
}
}
电源键监听
首先,我们是要获取系统权限
监听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) {
}
}