英文:
Activity crashed if we close it (back) before java thread completes the task
问题
我在OnCreate方法中创建了一个线程,然后在任务结束后对活动的UI进行更改。任务需要5-6秒,所以我使用了这个线程。
以下是代码部分:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final String folderSize = calculateFolderSize(); // 我的任务
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(folderSize + " GB");
}
});
}
});
thread.start();
一切都正常运行,我启动活动,然后计算大小,然后textView得到更新并显示大小。平均需要6秒钟。
问题 - 当我打开活动时,线程会在OnCreate方法中启动。如果在线程完成之前按下返回按钮,应用程序会在6秒钟后崩溃(当线程完成其工作时)。
解决这个问题的方法是什么?是否有任何替代方法,或者我需要在该活动中的返回按钮按下时停止线程。
英文:
I created a thread in Oncreate of an activity and then after the task ends then it makes changes to the UI of the activity. The task takes 5-6 seconds that's why I used the thread.
Here is the code:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final String folderSize = calculateFolderSize(); // my work
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(folderSize + " GB");
}
});
}
});
thread.start();
Everything works fine, I start the activity then the size is calculated and then the textView gets updated and shows the size. It takes 6 seconds on average.
The problem - when I open the activity then the thread starts in the OnCreate method. If I press the back button before the thread completes then my application crashes in 6 seconds (when the thread completes its work).
What is the solution to this problem, is there any alternative or I need to stop the thread in back pressed in that activity.
答案1
得分: 1
看起来你的runOnUiThread
代码在Activity被销毁后被调用。
你应该检查Activity是否被销毁:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final String folderSize = calculateFolderSize(); // 我的工作
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isDestroyed())
textView.setText(folderSize + " GB");
}
});
}
});
thread.start();
英文:
It appears that your runOnUiThread
code invokes after activity gets destroyed.
You should check if activity is destroyed:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
final String folderSize = calculateFolderSize(); // my work
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isDestroyed())
textView.setText(folderSize + " GB");
}
});
}
});
thread.start();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论