我使用工作线程从 url 读取文本。我的线程如下。在第一次运行时,我确信线程运行已完成,因为我可以检查 sdcard_readstr
为 null
。
第二次运行时,当我调用thread_download.start();
时,程序崩溃了。
可能出什么问题了?谢谢
public class DownloadingThread extends AbstractDataDownloading {
@Override
public void doRun() {
// TODO Auto-generated method stub
try {
// Create a URL for the desired page
URL url = new URL(SDcard_DetailView.textfileurl);
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new
InputStreamReader(url.openStream()));
do{
sdcard_readstr = in.readLine();
}while(sdcard_readstr!=null);
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
}
public abstract class AbstractDataDownloading extends Thread{
private final Set<ThreadCompleteListener> listeners
= new CopyOnWriteArraySet<ThreadCompleteListener>();
public final void addListener(final ThreadCompleteListener listener) {
listeners.add(listener);
}
public final void removeListener(final ThreadCompleteListener listener) {
listeners.remove(listener);
}
private final void notifyListeners() {
for (ThreadCompleteListener listener : listeners) {
listener.notifyOfThreadComplete(this);
}
}
@Override
public final void run() {
try {
doRun();
} finally {
notifyListeners();
}
}
public abstract void doRun();
}
编辑1:
在我的线程完成通知中,我使用 runOnUiThread
来使用 UI 组件。
这会引起问题吗?
public void notifyOfThreadComplete(Thread thread) {
// TODO Auto-generated method stub
if(downloadingStopbuttonispressed == false){//background process completed
textfileurl = null;
this.runOnUiThread(new Runnable() {
public void run() {
Wifibutton = (Button) findViewById(R.id.Wifiscanning);
Wifibutton.setText("Load another day's data");
final MenuItem refreshItem = optionsMenu.findItem(R.id.airport_menuRefresh);
refreshItem.setActionView(null);
}
});
}
}
我在 onResume() 中将线程启动称为
@Override
protected void onResume() {
super.onResume();
if(textfileurl != null){
Wifibutton.setText("Stop Data Loading");
buttonStatus = "loading";
setRefreshActionButtonState(true);
thread_download.start();
}
}
编辑2: 附上我的 LogCat 图像。
最佳答案
我的解决方案是here 。我无法第二次重用 Thread 对象的同一实例。我需要创建一个新实例来第二次调用Thread
。所以Thread适合单次运行的进程,对于多次运行的进程我应该使用AsyncTask
。即使 AsyncTack
仅用于一次执行,对于多次执行,我们应该使用 new MyAsyncTask().execute("");
我不明白为什么人们投反对票且没有给出任何理由。我在第一次搜索中找不到该链接。
关于android - 第二次运行线程使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21793120/