Detect home button press in android

后端 未结 17 2563
抹茶落季
抹茶落季 2020-11-22 08:22

This has been driving me nuts for a while now.

Is there any way of reliably detecting if the home button has been pressed in an android application?

Failing

17条回答
  •  星月不相逢
    2020-11-22 09:19

    Jack's answer is perfectly working for click event while longClick is considering is as menu button click.

    By the way, if anyone is wondering how to do via kotlin,

    class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
        private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
        private var mReceiver: InnerReceiver = InnerReceiver()
    
        fun startWatch() {
            context.registerReceiver(mReceiver, mFilter)
        }
    
        fun stopWatch() {
            context.unregisterReceiver(mReceiver)
        }
    
        inner class InnerReceiver: BroadcastReceiver() {
            private val systemDialogReasonKey = "reason"
            private val systemDialogReasonHomeKey = "homekey"
            override fun onReceive(context: Context?, intent: Intent?) {
                val action = intent?.action
                if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                    val reason = intent.getStringExtra(systemDialogReasonKey)
                    if (reason != null && reason == systemDialogReasonHomeKey) {
                        listener.onHomeButtonClick()
                    }
                }
            }
        } 
    }
    

提交回复
热议问题