Dappa jack
Dappa jack

Reputation: 145

How can I stop MediaPlayer when I leave my application, but not when I move to another Activity (Android Studio)

I am trying to make an game on android studio where background music plays continuously even when you switch activities, but I want the music to stop when the user leaves the application. I searched through stackoverflow and I tried to use this solution i found from here below:

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }



    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

}

The sound form the MediaPlayer plays in all the activities the problem is that the sound doesn't stop when I leave the app with the home button or when i lock the phone only when I actually close the help.

Please any help would be appreciated.

Upvotes: 0

Views: 554

Answers (1)

Công Hải
Công Hải

Reputation: 5241

You can use process lifecycle to listen when app goes to background and stop it

  1. Add dependencies in your build.gradle
    implementation "androidx.lifecycle:lifecycle-process:2.2.0"
  1. Create custom Application, don't forget to declare it in AndroidManifest
    public class CustomApplication extends Application implements LifecycleObserver {
        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onAppBackgrounded() {
            // your app come to background
            stopService(new Intent(this, BackgroundSoundService.class));
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onAppForegrounded() {
            // your app come to foreground
        }
    }

Upvotes: 1

Related Questions