gpt4 book ai didi

java - 退出应用程序时出现 IllegalStateException

转载 作者:行者123 更新时间:2023-11-30 02:21:23 27 4
gpt4 key购买 nike

我有 Runnable,它在 MediaPlayer ServiceThread 中运行。当我停止服务后退出应用程序时,我收到 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)

最佳答案

我通过一起删除新的 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);
}
};

在onPrepared

handler=new Handler();
handler.postDelayed(r, 1000);

在onDestroy中

handler.removeCallbacks(r);

感谢@Submersed 让我更多地思考逻辑,现在应用程序可以正常退出。

关于java - 退出应用程序时出现 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28506193/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com