停止从 BroadcastReceiver 启动的 Android 媒体播放器循环

Stop Android Media Player loop that is started from a BroadcastReceiver

我有一个 BroadcastReceiver 启动 MediaPlayer 并循环播放声音。我的问题是,当应用程序在后台运行并且接收器被触发时,播放器会播放声音。 现在,当我再次打开我的应用程序时,我想停止播放器。我试图向 Activity 的 onResume 中的接收者发送消息,但播放器的实例为空。如何在启动/重新打开我的应用程序时停止播放器?

尝试从 Service 控制 MediaPlayer 并使用 Context.startService() 和 Context.stopService() 并在其生命周期中处理 MediaPlayer

使用这个意图:

final Intent mpServiceIntent = new Intent(context, MPService.class);

当您的 BroadcastReceiver 被触发时使用:

startService(mpServiceIntent);

当 Activity.onCreate() 调用时使用:

stopService(mpServiceIntent);