The solution is here: Activity handle when screen unlocked
By registering a BroadcastReceiver filtering the Intent.ACTION_SCREEN_ON, Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_PRESENT actions, you will be able to handle these 3 cases:
Intent.ACTION_SCREEN_OFF: When the POWER button is pressed and the screen goes black.
Intent.ACTION_SCREEN_ON: When the POWER button is pressed again and lockscreen is showed up.
Intent.ACTION_SCREEN_PRESENT: When you pass the locksreen and are back in your game.
However, in my case (using a Galaxy S GT I9000 with Froyo 2.2) these actions are not called when dealing with the HOME button (and I think it's a general behavior).
One simple and quick (but maybe not the best) way to handle both HOME and POWER buttons to pause and resume your music could be to keep the onPause and onResume methods and use a simple boolean flag like this:
private boolean mPowerButton = false;
@Override
public void onPause() {
super.onPause();
// Pause your music
Log.d("Game activity", "Music paused");
}
@Override
public void onResume() {
super.onResume();
if (!this.mPowerButton) {
// Resume your music
Log.d("Game activity", "[HOME button] Music resumed inside onResume");
}
}
public class receiverScreen extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// This is the lockscreen, onResume has been already called at this
// step but the mPowerButton boolean prevented the resumption of music
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
LevelActivity.this.mPowerButton = true;
}
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
// Resume your music
Log.d("Game activity", "[POWER button] Music resumed inside ACTION_USER_PRESENT action");
LevelActivity.this.mPowerButton = false;
}
}
}
Hope it helps!