2010-02-12 150 views
1

我正在開發一個Android應用程序,我在後臺運行一個新線程時出現問題。Android線程在後臺

我做一類以下代碼:

public class Downloader implements Runnable { 

private Vector <DownloadRequest>messages = new Vector<DownloadRequest>(); 
static final int MAXQUEUE = 5; 
ApiRequest mApi; 


public void run() { 
    try { 
     while (true) { 
      getMessage(); 
     } 
    } 
    catch(ErrorException e) { } 
} 
private synchronized void getMessage() throws ErrorException{ 
    try { 
     notify(); 
     Log.d("DOWNLOADER", "empiezo a coger los mensajes"); 
     while (messages.size() == 0) 
      wait(); 
     DownloadRequest dr = messages.firstElement(); 
     mApi.setMethod(dr.getRequest()); 
     try { 
      mApi.executeRequest(); 
     } catch (ErrorException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Object o = dr.getObject(); 
     o.notify(); 
     return; 
    }catch(InterruptedException e) { 
     throw new ErrorException(); 

    } 

目的是等待接收新的消息,並調用API。

這個對象在一個新線程運行在這個活動

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.view); 
    mDownloader = new Downloader(new ApiRequest()); 
    Thread thread = new Thread(mDownloader); 
    thread.start(); 
    DownloadRequest dr = new DownloadRequest(this,TRIPS_METHOD); 
    try { 
     mDownloader.putMessage(dr); 

但當thread.start()被稱爲UI仍然受阻。我認爲這不應該發生,因爲是一個新線程。

任何人都可以幫助我嗎?

謝謝

回答

2

你用這個預先建立的類更好。在Android中,AsyncTask可處理後臺線程池和工作隊列。如果您絕對認爲您必須自行創建線程,請使用LinkedBlockingQueue而不是試圖同步訪問Vector。如果您想了解更多關於這個主題的信息,有幾本關於Java併發性的書籍。