Android 进阶Android Home 键监听

Posted 小哇壁纸

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 键监听的主要内容,如果未能解决你的问题,请参考以下文章

我的渲染技术进阶之旅如何在Windows系统编译Filament的android版本程序?

我的渲染技术进阶之旅如何在Windows系统编译Filament的android版本程序?

Android 高级进阶(源码剖析篇)

Android项目实战Android开发进阶学习

[Android进阶]Android性能优化

Android工程师进阶之路 :《Android开发进阶:从小工到专家》上市啦!