我在Runnable
Thread
的{{1}}中有MediaPlayer
个Service
。当我停止服务后退出应用程序时,我得到一个IllegalStateException。
这里是Runnable
Runnable runnable = new Runnable() {
public void run() {
while (isActive) {
while (progressStatus < 1000) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
if (result != null) {
result.putInt(UIFragment.MAX_KEY, mPlayer.getDuration());
result.putInt(UIFragment.PROGRESS_KEY, mPlayer.getCurrentPosition());
progressReciever.send(UIFragment.RESULT_DATA_RETURNED, result);
} else {
Log.d("Player", "is null");
}
}
});
try {
// Sleep for 200 milliseconds.
//Just to display the progress slowly
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
以下是onPrepared
handler=new Handler();
thread= new Thread(runnable);
thread.start();
在我的onDestroy
我打电话
handler.removeCallbacks(runnable);
thread.interrupt();
修改 栈跟踪
02-13 00:04:19.722 13929-13929/com.brianstacks.servicefundamentals E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.brianstacks.servicefundamentals, PID: 13929
java.lang.IllegalStateException
at android.media.MediaPlayer.getDuration(Native Method)
at com.brianstacks.servicefundamentals.services.MusicPlayerService$1$1.run(MusicPlayerService.java:65)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
答案 0 :(得分:1)
我通过一起移除新的Thread
来修复它,只让Handler
控制Runnable
以下是代码:
private Runnable r = new Runnable() {
public void run() {
if (result != null) {
result.putInt(UIFragment.MAX_KEY, mPlayer.getDuration());
result.putInt(UIFragment.PROGRESS_KEY, mPlayer.getCurrentPosition());
progressReciever.send(UIFragment.RESULT_DATA_RETURNED, result);
} else {
Log.d("Player", "is null");
}
handler.postDelayed(this, 1000);
}
};
in onPrepared
handler=new Handler();
handler.postDelayed(r, 1000);
在onDestroy中
handler.removeCallbacks(r);
现在app退出时没有任何错误,感谢@Submersed让我更多地思考逻辑。