媒体播放器服务在崩溃后继续播放

时间:2021-07-18 08:46:25

标签: service crash ondestroy

在我的后台服务中,当 mp.release() 在 onDestroy() 中没有执行时,MediaPlayer 在几秒钟内停止播放。在 onDestroy() 中执行 mp.release() 时,MediaPlayer 继续播放,但它也会使应用程序崩溃。

如何让 MediaPlayer 在后台播放并且无论 mp.start() 是否完成都始终执行 stopSelf()?

    public class MyService extends Service {
private Looper serviceLooper;
private ServiceHandler serviceHandler;
private static final String TAG = "BackgroundSoundService";
private MediaPlayer mp;

// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        String url = "https://livestream.mediaworks.nz/radio_origin/sound_128kbps/chunklist.m3u8"; // your URL here
        MediaPlayer mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC); //to send the object to the initialized state
        try {
            mp.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            mp.prepare(); // might take long! (for buffering, etc)
        } catch (IOException e) {
            e.printStackTrace();
        }
        mp.start();

        // Stop the service using the startId, so that we don't stop
        // the service in the middle of handling another job
        stopSelf(msg.arg1);
  }
}

    @Override
public void onDestroy() {
   //      if (mp != null) {
      mp.release();
   //         mp = null;
  //       }
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
   }
 }

0 个答案:

没有答案