如何停止使用 MediaPlayer 同时播放多首歌曲的服务列表中的多个 android 服务?

How to stop multiple android services in a List of services that use MediaPlayer to play many songs simultaneously?

大家好,如果之前有人问过这个问题,我很抱歉,但我已经阅读了 3 个多小时的其他答案和文档,但没有成功,我真的找不到解决这个问题的方法。

描述

所以我有这个列表:

private List<MusicService> songList;

并添加我需要的所有服务:

private Intent rainIntent;
private Intent stormIntent;
private Intent oceanIntent;

然后我初始化它们:

    rainIntent = new Intent(this, MusicService.class);
    stormIntent = new Intent(this, MusicService.class);
    oceanIntent = new Intent(this, MusicService.class);

然后我把我要播放的歌曲的ID传给他们onStartCommand()

    rainIntent.putExtra(MusicService.SONG_ID, R.raw.rain);
    songsIntentsList.add(rainIntent);
    stormIntent.putExtra(MusicService.SONG_ID, R.raw.thunder);
    songsIntentsList.add(stormIntent);
    oceanIntent.putExtra(MusicService.SONG_ID, R.raw.ocean);
    songsIntentsList.add(oceanIntent);

当我使用列表启动所有服务时没有问题,这工作正常:

private void startSongsServices() {

    for (Intent intent : songsIntentsList) {
        context.startService(intent);
    }

}

我的问题:

但是当尝试使用 stopService() 时它不起作用我该怎么办?就像下面这样:

private void stopSongsServices() {

    for (Intent intent : songsIntentsList) {
        context.stopService(intent);
    }

}

这是 MusicService 的 class:

public class MusicService extends Service {


    private MediaPlayer mMediaPlayer = null;

    public static String SONG_ID = null;


    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int id = intent.getExtras().getInt(SONG_ID);

        mMediaPlayer = MediaPlayer.create(this,id);


        if (!mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();

        }

        return START_STICKY; //START_STICKY makes service run until we call onDestroy() service to stop it
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

如何在需要时停止所有这些服务?

How can I stop all this services when needed?

您只有一项服务。服务是天生的单例。您的三个 startService() 调用导致了 MusicService 的一个实例。第一个 startService() 调用会创建实例(并且 onCreate() 会被调用),另外两个 startService() 调用只会向 运行 服务实例发送命令。因此,onStartCommand() 将在那个实例上被调用三次,因此您创建了一个 MediaPlayer 的三个实例...并且只保留对最后一个实例的引用。

如果你想每个命令有一个 MediaPlayer 个实例,欢迎你这样做,但你需要保留 所有 个实例,这样你就可以在 onDestroy().

中清理 所有

onDestroy 只会被调用一次。

您需要跟踪正在创建的媒体播放器对象并在 loop.Right 中停止它们,现在您正在创建 3 个媒体播放器对象(onStartCommand 被调用 3 次)但只释放一个。

类似下面的内容

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    int id = intent.getExtras().getInt(SONG_ID);

    mMediaPlayer = MediaPlayer.create(this,id);
    mediaPlayerObjectsList.add(mMediaPlayer);
}

然后在 onDestroy() 中做这样的事情:

  for (MediaPlayer player : mediaPlayerObjectsList) {
        player.release();
    }