2012-03-16 54 views
0

我是Android編程和線程的新手。我想從遠程服務器獲取圖片並顯示它。 (迄今爲止的作品^^) 但圖片來自相機,所以我需要一個新的,只要我展示我之前下載的一個。這意味着,線程永遠不應該停止抓圖片。 (只要活動存在。)
另外我只想建立到服務器的一個連接,然後只需執行HTTP-gets。所以我必須有一個Thread可以使用的參數「連接」。Android - 反覆執行線程

爲了得到一個想法 - 它應該工作是這樣的(但顯然事實並非如此):

private class DownloadImageTask extends AsyncTask<URLConnection, Void, Bitmap> { 
    /** The system calls this to perform work in a worker thread and 
     * delivers it the parameters given to AsyncTask.execute() */ 
    private URLConnection connection = null; 
    protected Bitmap doInBackground(URLConnection...connection) { 
     this.connection = connection[0]; 
     return getImageFromServer(connection[0]); 
    } 
    protected void onPostExecute(Bitmap result) { 
     pic.setImageBitmap(result); 
     this.doInBackground(connection); 
    } 
} 

回答

0

可能會更好地使用Thread在這裏,因爲AsyncTask是當任務在某個時候結束。像下面的東西可以爲你工作。除此之外,你可以使用本地Service

protected volatile boolean keepRunning = true; 
private Runnable r = new Runnable() { 
    public void run() { 
     // methods are a bit bogus but it should you give an idea. 
     UrlConnection c = createNewUrlConnection(); 
     while (keepRunning) { 
      Bitmap result = getImageFromServer(c); 
      // that probably needs to be wrapped in runOnUiThread() 
      pic.setImageBitmap(result); 
     } 
     c.close(); 
    } 
}; 
private Thread t = null; 

onResume() { 
    keepRunning = true; 
    t = new Thread(r); 
    t.start(); 
} 

onPause() { 
    keepRunning = false; 
    t = null; 
} 
+0

謝謝,這幫了我很多! – user1271544 2012-03-16 13:08:59

+0

還有一件事情...沒有'c.close();'我如何關閉'URLConnection'?到目前爲止我已經找到了一些東西。 – user1271544 2012-03-16 13:21:53

+0

嗯,那麼你應該得到'InputStream'上應該有'.close()'。你應該總是關閉你打開的東西 - 這就是爲什麼我添加了一個關閉:) – zapl 2012-03-16 13:44:44

0

你應該爲它設置一些延遲,但要解決這個問題,我認爲它應該是這樣的:

private class DownloadImageTask extends AsyncTask<URLConnection, Void, Bitmap> { 
/** The system calls this to perform work in a worker thread and 
    * delivers it the parameters given to AsyncTask.execute() */ 
private URLConnection connection = null; 
protected Bitmap doInBackground(URLConnection...connection) { 
    this.connection = connection[0]; 
    return getImageFromServer(connection[0]); 
} 
protected void onPostExecute(Bitmap result) { 
    pic.setImageBitmap(result); 
    this.execute("..."); 
} 
} 
+0

嗨,現在我得到這個錯誤:無法執行任務。該任務已在運行。 – user1271544 2012-03-16 11:32:31

+0

也許嘗試先取消任務。 – goodm 2012-03-16 11:37:06

0

異步任務只能執行一次會更好...... 任務只能執行一次(如果第二試圖執行一個異常將被拋出。 ) 看到這個..上的AsyncTask documentation on AsyncTask 文檔,我建議最好是,如果你使用的服務,下載... 甚至可以使用一個線程...

這樣

public void run() { 
    while (true) { 
     //get image... 
    } 
}