问题描述
在我的后台服务中,当 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();
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)