I am developing an application for music. I have an Activity where I have a list with tracks. I can select a track and then I move to another activity in order to play the selected track. I also have a Service class and when I press the home button, I want it to start the service (play music in the background) and move to the home screen.
Also, I have the method OnBackPressed() in order to move to the previous Activity.
How, I can intercept the home button press? Thanks, for yours answers.
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’sonPause()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:
Edit: Give this a try as a workaround for not being able to intercept the home button, set a
back_flagAgain, if it’s not registering the home, this is the only work around I can think of at the moment.