Rather than catching the home button press, you might want to flesh out the android lifecycle a little more and use onPause()
instead. If you override the activity's onPause()
method to start the service, whenever the user leaves the activity temporarily, i.e. goes "home", that should get you what you need without having to catch all the button presses.
If you want the service to start whenever the user leaves the activity and, say, goes to another application, the lifecycle is your friend. You might want to consider what happens when the user gets an email notification and leaves your application that way. Do you want the service to start then as well? The user didn't hit the home button so your service won't start, but they did leave your application. Do you want the service to start in that scenario?
It sounds like you want the service to start whenever the user leaves that activity, so please look at overriding onPause()
if that is the case.
More on the android life cycle here:
http://developer.android.com/reference/android/app/Activity.html
All you would need is to add this method:
@Override
protected void onPause(){
<start your service here>
}
Edit: Give this a try as a workaround for not being able to intercept the home button, set a back_flag
public class Your_Activity extends Activity {
private boolean back_flag = false;
.
.
.
public void onBackPressed(){
back_flag = true;
<whatever else you have in onBackPressed()>
}
@Override
protected void onPause(){
if(!back_flag){
<start your service>
}
back_flag = false;
super.onPause();
}
}
Again, if it's not registering the home, this is the only work around I can think of at the moment.