一、home键的监听
(1)在4.0系统以下,可以直接用下面的方法,网上很多,自己整理了一下:
Android Home键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,做法就是:
先禁止Home键,再在onKeyDown里处理按键值,点击Home键的时候就把程序关闭,或者其他的操作。
加权限禁止Home键
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(KeyEvent.KEYCODE_HOME==keyCode){
/* android.os.Process.killProcess(android.os.Process.myPid());*/
//关闭程序或做其他操作.
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onAttachedToWindow(){
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
(2)如果系统是4.x.x,上面的方法就会失去作用。但我们可以通过监听系统的广播来实现,这个方法2.x——4.x都适用。
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());
}
}
ok,关于home键的情况就这些了,试验结果是可行的,参考链接:
http://blog.csdn.net/haifei0801/article/details/7764438
http://www.cnblogs.com/jyshi/archive/2011/07/13/2139408.html
二、电源键的监听
首先,我们是要获取系统权限
<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());
}
}