androidaudio-playerscreen-offandroid-music-player

Android how to stop music when screen is off


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.


Solution

  • 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.