Android中Home键的监听

在android中监听是否点击了Home键,按照以下几步就可以实现:

1、新建一个广播接收者,代码如下:
 internal inner class InnerRecevier : BroadcastReceiver() {

        val SYSTEM_DIALOG_REASON_KEY = "reason"

        val SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"

        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS == action) {
                val reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY)
                if (reason != null) {
                    if (reason == SYSTEM_DIALOG_REASON_HOME_KEY) {
                        Toast.makeText(this@HistoryGameDetailActivity, "点击了Home键", 
                        Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
2、注册广播:
 //创建广播
        innerReceiver = InnerRecevier()
        //动态注册广播
        val intentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
        //启动广播
        registerReceiver(innerReceiver, intentFilter)
3、最后别忘了取消注册:
  if (innerReceiver != null) {
        unregisterReceiver(innerReceiver)
    }

效果图如下:


Home键监听.png

你可能感兴趣的:(Android中Home键的监听)