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
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()
}
}
}
}
}
onUserLeaveHint();
override this activity class method.This will detect the home key click . This method is called right before the activity's onPause() callback.But it will not be called when an activity is interrupted like a in-call activity comes into foreground, apart from that interruptions it will call when user click home key.
@Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
Log.d(TAG, "home key clicked");
}
This works for me. You can override onUserLeaveHint method https://www.tutorialspoint.com/detect-home-button-press-in-android
@Override
protected void onUserLeaveHint() {
//
super.onUserLeaveHint();
}
This is an old question but it might help someone.
@Override
protected void onUserLeaveHint()
{
Log.d("onUserLeaveHint","Home button pressed");
super.onUserLeaveHint();
}
According to the documentation, the onUserLeaveHint() method is called when the user clicks the home button OR when something interrupts your application (like an incoming phone call).
This works for me.. :)
You might consider a solution by Andreas Shrade in his post on How-To Create a Working Kiosk Mode in Android. It's a bit hacky, but given the reasons that interception of the home button is prevented it has to be ;)