2010-09-21 35 views
1

我使用的代碼類似於下面的內容,除了線程是通過按鈕啓動啓動的。當我按下按鈕時,url上的數據被抓取,它將我切換到另一個活動。我遇到的問題是,當我在其他活動,並擊中後退時,我得到一個例外說,線程已經開始。我已經嘗試殺死線程,當活動加載檢查isAlive時,但它似乎不會死。有沒有人碰巧知道如何讓這個活動返回到原來的狀態,創建的線程不運行?異常導致的後退按鈕按下(Android)上仍然運行的線程

import java.io.BufferedInputStream; 
import java.io.InputStream; 
import java.net.URL; 
import java.net.URLConnection; 
import org.apache.http.util.ByteArrayBuffer; 

public class Iconic extends Activity { 
private String html = ""; 
private Handler mHandler; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    mHandler = new Handler(); 
    checkUpdate.start(); 
} 

private Thread checkUpdate = new Thread() { 
    public void run() { 
     try { 
      URL updateURL = new URL("http://iconic.4feets.com/update"); 
      URLConnection conn = updateURL.openConnection(); 
      InputStream is = conn.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      ByteArrayBuffer baf = new ByteArrayBuffer(50); 

      int current = 0; 
      while((current = bis.read()) != -1){ 
       baf.append((byte)current); 
      } 

      /* Convert the Bytes read to a String. */ 
      html = new String(baf.toByteArray()); 
      mHandler.post(showUpdate); 
     } catch (Exception e) { 
     } 
    } 
}; 

private Runnable showUpdate = new Runnable(){ 
    public void run(){ 
     Intent newIntent = New Intent(Iconic.this, otherClass.class); 
     startActivity(newIntent); 
    } 
}; 

}

回答

1

我也有類似的問題,我的應用程序之一:我是在不同的線程在做什麼,而線程運行的用戶將切換到橫向模式下創建一個新的活動。線程完成後,應用程序將強制關閉,因爲線程指向不再存在的活動。

我對這個問題的解決方案是使用AsyncTask。基本上,它抽象了一個線程和一個處理程序,並允許您獲取後臺任務的定期進度更新(即實現類似ProgressBar的東西)。我還從Activity.onDestroy()方法中調用了AsyncTask.cancel(),所以當活動被銷燬時,AsyncTask將停止運行。

0

在這種情況下,您不必跨越一個新線程來啓動活動。 .rather

在spaned線程爲此

{ 。

progressHandler.sendMessage(progressHandler.obtainMessage());

}

處理器progressHandler =新的處理程序(){ 公共無效的handleMessage(最終信息MSG){

 Intent newIntent = New Intent(Iconic.this, otherClass.class); 
    startActivity(newIntent); 

    } 
}; 
0

不能調用。開始()在同一個線程實例的兩倍。你有沒有試過重新創建它?

...

checkUpdate = new Thread(checkUpdateRunnable).start(); 

...

private Runnable checkUpdateRunnable = new Runnable() { 
    public void run() { 

...

希望幫助, 再見!

0

您應該在服務中運行線程。 This video(來自Google I/O 2010)對於如何設計Android應用程序架構中的Android活動生命週期和服務非常有用。

0

我有同樣的問題,但對於當前的實例,我已經創建了以下解決方案。我知道這很尷尬,但如果你知道正確的方法,那麼請教我。還有一點我已經讀過,除非它包含了將來的任務,否則你無法停止使用Java的線程。像ExecutorService線程...這是真的嗎?

public void surfaceCreated(SurfaceHolder holder) { 
     try{ 
     _thread.setRunning(true); 
     _thread.start(); 
     }catch(Exception ex){ 
      _thread = new TutorialThread(getHolder(), this); 
      _thread.start(); 
     } 

    }