android开发对Home键进行监听

以下只是我解决问题过程中的一点点个人总结,点滴积累,贵在坚持,感谢你的阅览!

Home 键是一个比较偏向于系统做处理的键,与 Back 键不一样,一般的在 onKeyDown 和 onKeyUp 等方法中监听是无效的,下面是我在实际项目中通过问同事、查找资料、验证方法可行性等之后的两个监听方法;

监听 Home 键分两种情况:1.界面有弹窗,Activity 失去界面焦点;2.界面无弹窗,Activity 取得界面焦点;

1.界面有弹窗,以 dialog 为例,dialog 获取了 Activity 的焦点,此时监听 Home 键可为 dialog 注册监听器:

mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_HOME && event.getRepeatCount() == 0 && mDialog.isShowing()){
                    // TODO dialog弹出期间用户点击了 home 键
                    Toast.makeText(this,"点击 Home 键",Toast.LENGTH_SHORT).show(); return true;
                }
                return false;
            }
        });

2.界面无弹窗,此情况下可动态注册监听 Home 键的广播:

步骤1:在 Avtivity 内新建广播类:HomeWatcherReceiver;

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();
            if (TextUtils.equals(intentAction, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (TextUtils.equals(SYSTEM_DIALOG_REASON_HOME_KEY, reason)) {
                    //TODO 用户点击了 home 键
                    Toast.makeText(this,"点击 Home 键",Toast.LENGTH_SHORT).show();
                 }
            }
        }
    }

2.新建全局变量

private HomeWatcherReceiver mHomeWatcherReceiver = null;

3.在 Activity 的 onCreate 生命周期中 注册广播:

mHomeWatcherReceiver = new HomeWatcherReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mHomeWatcherReceiver, filter);

4.在 Activity 的 onDestory 中解除注册:

if (mHomeWatcherReceiver != null) {
            try {
                unregisterReceiver(mHomeWatcherReceiver);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }











你可能感兴趣的:(方法,小方法封装,个人积累,java程序)