[英]How to stop a MediaPlayer when I go to next activity in Android studio
[英]How can I stop MediaPlayer when I leave my application, but not when I move to another Activity (Android Studio)
我正在尝试在 android 工作室制作游戏,即使您切换活动,背景音乐也会连续播放,但我希望在用户离开应用程序时音乐停止。 我搜索了stackoverflow,并尝试使用从下面找到的解决方案:
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();
}
}
MediaPlayer 在所有活动中播放的声音问题是当我使用主页按钮离开应用程序或仅在我实际关闭帮助时锁定手机时声音不会停止。
请任何帮助将不胜感激。
您可以使用进程生命周期来监听应用程序何时进入后台并停止它
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.