2

I'm developing an android application in which when the app is in background it displays on the status bar a notification. Using onUserLeaveHint I can detect when the user presses the HOME button, but the same event listener also triggered when the user presses the BACK Button. How can I detect HOME button presses only?

Royi Benyossef
  • 769
  • 5
  • 18
Manuel Castro
  • 1,633
  • 3
  • 24
  • 38

4 Answers4

2

I'm sorry to say but all the suggested answers are obsolete and some of them are downright wrong.

Intercepting HOME directly was blocked way back on Froyo due to security issues and a fear of malware (if you can intercept HOME you can try and hijack the device).

The only solution i'm aware of which seperates BACK from HOME is to to intercept the onNewIntent() event listener.

onNewIntent() is fired when an app is running, and receives another intent to be launched. That is why you will get it when HOME is pressed.

When BACK is pressed, your app is not going to receive an intent. All that happens is that the apps on top of yours are removed. So your app appears from the back stack with only onResume() being called.

So that is how you can tell.

It is also mentioned here. Goodluck.

Community
  • 1
  • 1
Royi Benyossef
  • 769
  • 5
  • 18
0

When the user presses back, you should receive a call to onBackPresssed. You could use this to set a flag so that you can determine during onUserLeaveHint if the back button was pressed. Remember to clear the flag afterwards.

Tunga
  • 1,014
  • 9
  • 10
0

I found a solution using the onStop() and onResume() method. That's my code

@Override
public void onBackPressed() {
    Intent intent = new Intent(this, PagerActivity.class);
    startActivity(intent);
    finish();
}

/* Handle notification create/destroy */
private Boolean notificationCreated = false;

@Override
protected void onStop() {
    Utils.createNotification();
    notificationCreated = true;
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    if (notificationCreated)
    {
        Utils.cancelNotification();
        notificationCreated = false;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (notificationCreated) {
        Utils.cancelNotification();
        notificationCreated = false;
    }
}
Manuel Castro
  • 1,633
  • 3
  • 24
  • 38
-2

You can just simply deactivate the back button for that specific page. Here is what works for me:

@Override
public void onBackPressed() {

}
Zelalem
  • 392
  • 5
  • 7
  • Overriding the `onBackPressed` is against the Android app checklist (http://developer.android.com/distribute/essentials/quality/core.html) App does not redefine the expected function of a system icon (such as the Back button). – Royi Benyossef Apr 16 '15 at 13:54