【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();
            }
        }
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值