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
CodePudding user response:
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
CodePudding user response:
use onPause() then make it stop playing music, after that onResume or onStart to play the music if user is back to app