-3

My music stop when I press home button but when the screen is off it is playing. How can I stop this? And restore when the screen is on.

Community
  • 1
  • 1
Seravier
  • 145
  • 1
  • 2
  • 11

2 Answers2

0

Create a service in background, create a single instance of soundPlayer. In the service check which is the Activity in focus. If the package does not belong to your Application, then stop the music.

Shishir Shetty
  • 2,021
  • 3
  • 20
  • 35
0

You need to programmatically register a BroadcastReceiver to receive the ACTION_SCREEN_OFF and ACTION_SCREEN_ON intent actions. You can not register a receiver in your AndroidManifest.xml for these actions.

private BroadcastReceiver screenOffReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (Intent.ACTION_SCREEN_OFF.equals(action) {
            // do stuff
        }
    }
};

// to register the receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
context.registerReceiver(screenOffReceiver, filter);

Hopefully you are playing music in a Service, in which case you can register the screen off receiver when your music starts. Service extends Context, so you can call registerReceiver directly.

Karakuri
  • 38,365
  • 12
  • 84
  • 104