I have an android app that starts playing music right after the splash screen all the time while the user interacts with the app, using a singleton class for MediaPlayer
, which is working perfectly, but I want to stop the music when the app exits or user switched to the other app, unfortunately which is not working properly, and I have to kill the app from the recent task to stop the music
Asked
Active
Viewed 202 times
1

hata
- 11,633
- 6
- 46
- 69

Ali Tamoor
- 896
- 12
- 18
2 Answers
1
If you have multiple activities while user is running the application, use LifecycleObserver
to observe the state change in application class.
implementation "androidx.lifecycle:lifecycle-extensions:2.4.0"
Application Class
public class MyApplication extends Application implements LifecycleObserver {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
// Application level lifecycle events
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnteredForeground() {
//Log.d(TAG,"Application did enter foreground");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnteredBackground() {
// Log.d(TAG,"Application did enter background");
}
}
For more info refer to - Handling lifecycle with Lifecycle Observers

Nitish
- 3,075
- 3
- 13
- 28
0
use onPause() then make it stop playing music, after that onResume or onStart to play the music if user is back to app

MiniDev99
- 324
- 1
- 13