ANDROID 返回,選單和HOME鍵的監聽
------網上找了很多資料,專案中使用,最後將經驗總結如下:
1,返回和選單鍵是可以直接重寫onKeyDown(int keyCode, KeyEvent event) 方法監聽:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { // 監控/攔截/遮蔽返回鍵
//do something
} else if (keyCode == KeyEvent.KEYCODE_MENU) {
//do something
} else if (keyCode == KeyEvent.KEYCODE_HOME) {
//這裡操作是沒有返回結果的
}
return super.onKeyDown(keyCode, event);
}
在do something 中,如果返回false則時間不繼續傳遞,也就是不會觸發相應的後續事件
2,如果是Home事件,看網上的說法,是底層攔截了這個事件,但是攔截後會發出一個廣播。所以註冊個廣播接收HOME按鍵事件就行了。
/**
* Home鍵監聽封裝
*
*
*/
public class HomeListener {
static final String TAG = "HomeListener";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
// 回撥介面
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
public HomeListener(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
/**
* 設定監聽
*
* @param listener
*/
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
/**
* 開始監聽,註冊廣播
*/
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
/**
* 停止監聽,登出廣播
*/
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
/**
* 廣播接收者
*/
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
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) {
// Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// 短按home鍵
mListener.onHomePressed();
} else if (reason
.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
// 長按home鍵
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
在使用的時候:
private HomeListener mHomeWatcher;
在oncreate()中:
mHomeWatcher = new HomeListener(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
@Override
public void onHomePressed() {
if(null!=vibrator){
vibrator.cancel();
}
if(null!=timer){
timer.cancel();
}
}
@Override
public void onHomeLongPressed() {
if(null!=vibrator){
vibrator.cancel();
}
if(null!=timer){
timer.cancel();
}
}
});
mHomeWatcher.startWatch();
在onpause()方法中:
mHomeWatcher.stopWatch();