Android 进阶Android Home 键监听

炒沙作縻终不饱,缕冰文章费工巧。这篇文章主要讲述Android 进阶Android Home 键监听相关的知识,希望能为你提供帮助。
android Home键监听Android 普通键值可以直接在dispatchKeyEvent()中处理,但Home键,比较特殊,需要单独监听其广播,且必须为动态广播,其静态广播无效;
需求:Home键,设置 Kill 自己,但设置中有多个Activity,在每个Activiy 中年监听Home键广播不现实,必须把监听广播抽取出来在同一个类中实现,考虑到BaseActivity;

public class BaseActivity extends Activity {private HomeWatcherReceiver mHomeWatcherReceiver = null; private boolean isNeedFinish = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(); }public void setBackFinish(boolean flag) { isNeedFinish = flag; }private void registerReceiver() { mHomeWatcherReceiver = new HomeWatcherReceiver(); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mHomeWatcherReceiver, filter); }@Override public boolean dispatchKeyEvent(KeyEvent event) {int KeyCode = event.getKeyCode(); if (event.getAction() == KeyEvent.ACTION_DOWN) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { this.finish(); System.gc(); return true; } } return super.dispatchKeyEvent(event); } public class HomeWatcherReceiver extends BroadcastReceiver {private static final String SYSTEM_DIALOG_REASON_KEY = "reason"; private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; @Override public void onReceive(Context context, Intent intent) {String intentAction = intent.getAction(); Log.i(MyAPP, "intentAction =" + intentAction); if (TextUtils.equals(intentAction, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); Log.i(MyAPP, "reason =" + reason); if (TextUtils.equals(SYSTEM_DIALOG_REASON_HOME_KEY, reason)) { BaseActivity.this.finish(); } } }}@Override protected void onDestroy() { super.onDestroy(); if (mHomeWatcherReceiver != null) { try { unregisterReceiver(mHomeWatcherReceiver); } catch (Exception e) { e.printStackTrace(); } } } }

【Android 进阶Android Home 键监听】 

    推荐阅读