1

My android application is a client, and when someone click the home button, I want to send a message to the server, and when the user changes back to the application, I also want to send a message to the server. If I could overwrite the HOME button keyEvent, or any method which will be called only when the application will be put into background, I could send message and set a static variable in a singleton which will be checked every onStart(), so basically I just need to somehow "override" the HOME button. I tried the followings:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_HOME) {
        //...
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

It does simply not work. I put a breakpoint in it, but HOME button doesn't trigger this method at all. (Samsung Galaxy Ace, android 2.2.1).

I also tried to overrite the onUserLeaveHint() like this:

@Override
protected void onUserLeaveHint() {
    //...
    super.onUserLeaveHint();
}

But the problem is, this method will be called not only when I press HOME button or the application is interrupted, but when I just navigate to an other activity (and finish the current one). Are there any solution to this problem?

Dénes
  • 113
  • 1
  • 1
  • 8

2 Answers2

4

Might want to take a look at this Android Docs

You are looking for onPause / onResume, based on the line

or any method which will be called only when the application will be put into background

That doc should explain how the stack works, which will allow you to accomplish this problem.

AJak
  • 3,863
  • 1
  • 19
  • 28
  • 1
    The problem with onPause, that this will be called, when I just simply change activity(and finish the current), not only when the application goes background. How to make difference between the two situation? – Dénes Dec 07 '12 at 22:22
  • Unfortunately Android doesn't have a applicationDidEnterBackground like iOS does. IMO, you're best off keeping track of your activities active status to determine if it is going into background or going to a new activity. There are a lot of topics regarding this on SO, with a lot of different ideas. I suggest looking around to find what works best for you. – AJak Dec 07 '12 at 22:46
  • thanks the answer, at least I wont try to find something thast doesnt exists. – Dénes Dec 08 '12 at 00:15
1

There is not an day solution to this problem, because android does not let you override the home button. The easiest way around this is to pur your code in onPause, but of course this can be called without the home button being pressed.

The second (not accepted) answer here has an interesting solution, but I have not tried it so I am not sure if it works

Community
  • 1
  • 1
jcw
  • 5,132
  • 7
  • 45
  • 54