用BroadcastReceiver监听home按钮方法
private class HomeButtonReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("homekeytest","HOME 被按下")
}
}
private var mHomeKeyReceiver: HomeButtonReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 注册Reciever
mHomeKeyReceiver = HomeButtonReceiver()
val filter:IntentFilter = IntentFilter()
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
registerReceiver(mHomeKeyReceiver, filter)
}
override fun onPause() {
super.onPause()
unregisterReceiver(mHomeKeyReceiver)
}
//onKeyDown方法,返回键按下时可以被检测到,但是检测不到home键
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
Log.d("onKeyDown", KeyEvent.keyCodeToString(keyCode))
when (keyCode) {
KeyEvent.KEYCODE_A -> {
//your Action code
return true
}
}
return super.onKeyDown(keyCode, event)
}
另外按下home键onUserLeaveHint事件也会被触发。
onUserLeaveHint事件当用户要离开当前activity的时候会被出发,比如按下home键,start另外一个activity时。
但是当电话来电时,或者当前activity finish时不会被触发。