Android 小技巧

Android 監聽 Back鍵、Home鍵、Menu鍵

Android 監聽 Back鍵、Home鍵、Menu鍵


1.Back鍵

Activity用法

override fun onBackPressed() {
    ToastUtil.toast("攔截妳")
}

Fragment用法

override fun onAttach(context: Context) {
    super.onAttach(context)

    val callback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            Toast.makeText(context, "攔截妳", Toast.LENGTH_SHORT).show()
        }
    }
    requireActivity().onBackPressedDispatcher.addCallback(this, callback)
}

2.Home鍵&Menu鍵

創建廣播接收者

class KeyReceiver : BroadcastReceiver() {
    val REASON = "reason"
    val HOMEKEY = "homekey"
    val RECENTAPPS = "recentapps"

    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.apply {
            val action = intent.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(REASON)

                if (TextUtils.equals(reason, HOMEKEY)) {
                    Toast.makeText(context, "HOME", Toast.LENGTH_SHORT).show()
                } else if (TextUtils.equals(reason, RECENTAPPS)) {
                    Toast.makeText(context, "MENU", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}

註冊接收者

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    registerReceiver(KeyReceiver(), IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS))
}

發表迴響