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.
You can use process lifecycle to listen when app goes to background and stop it
implementation "androidx.lifecycle:lifecycle-process:2.2.0"
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
}
}