2014-02-15 68 views
2

我使用工作线程从URL中读取文本。我的线程如下。在第一次运行时,我确信线程运行已完成,因为我可以检查sdcard_readstrnull。 在第二次运行时,当我拨打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的图像连接。 enter image description here

+0

为什么downvoted?请给我理由。哪里不对? – batuman

+0

你可以在DownloadingThread.start()被调用时显示代码吗? – dieend

+0

@dieend,我已更新到我原来的帖子。我在onResume()中调用线程启动。 – batuman

回答

3

我的解决方案是here。我不能在第二次重用Thread对象的同一个实例。我需要创建一个新实例来第二次调用Thread。所以Thread适用于单次运行过程,对于多次运行过程我应该使用AsyncTask。即使AsyncTack只是一次执行和多次执行,我们应该使用new MyAsyncTask().execute("");我不明白为什么人们没有理由给予downvote。我在第一次搜索时找不到链接。