2
我使用工作線程從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();
}
EDIT1: 在我的線程完成通知,我用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();
}
}
EDIT2: 我logcat的圖像連接。
爲什麼downvoted?請給我理由。哪裏不對? – batuman
你可以在DownloadingThread.start()被調用時顯示代碼嗎? – dieend
@dieend,我已更新到我原來的帖子。我在onResume()中調用線程啓動。 – batuman