2011-07-13 24 views
5

我在理解如何使用Looperprepare()/loop()/邏輯時遇到了一些問題。在Android中使用Looper.prepare()的細節

我有三個線程:一個是UI線程,一個是遊戲邏輯線程,最後一個是網絡通信線程(後臺線程,只在使用時才存在)。

遊戲線程對網絡調用的結果有很多依賴關係,所以我想將網絡線程從遊戲線程中取出,然後讓Handler發佈結果。

當然,由於UI線程沒有涉及我需要撥打Looper.prepare() ...某處。我認爲它應該在遊戲線程中被調用,但我不能這樣做,因爲loop()會接管它。

如何從網絡線程與我的處理程序回發到遊戲線程?

回答

7

發生了什麼事是,一旦你在一個線程調用Looper.prepare(),其次是Looper.loop(),所有的線程將永遠是服務其的MessageQueue,直到有人叫退出()在它的活套。

要認識到的另一件事是,在默認情況下,當處理器被實例化,它的代碼將始終有人在

你應該做的是創建一個新的線程,並在運行中創建的線程中執行( )調用Looper.prepare(),設置任何處理程序,然後調用Looper.loop()。

在這裏記住這些事情是我使用很多地方的基本模式。此外,您應該只需使用AsyncTask就可以了。

public class NetworkThread extends Thread { 
    private Handler mHandler; 
    private Handler mCallback; 
    private int QUIT = 0; 
    private int DOWNLOAD_FILE = 1; 
    public NetworkThread(Handler onDownloaded) { 
     mCallback = onDownloaded; 
    } 

    public void run() { 
     Looper.prepare(); 
     mHandler = new Handler() { 
      @Override 
      public void handleMessage(Message msg) { 
       switch (msg.what) { 
        // things that this thread should do 
        case QUIT: 
         Looper.myLooper().quit(); 
         break; 
        case DOWNLOAD_FILE: 
         // download the file 
         mCallback.sendMessage(/*result is ready*/); 
       } 
      } 
     } 
     Looper.loop(); 
    } 

    public void stopWorking() { 
     // construct message to send to mHandler that causes it to call 
     // Looper.myLooper().quit 
    } 

    public void downloadFile(String url) { 
     // construct a message to send to mHandler that will cause it to 
     // download the file 
    } 
} 
0

你能告訴一些你使用你的網絡線程的例子嗎?我認爲你可以在不使用Looper的情況下解決你的問題。

您可以使用ASyncTask執行後臺任務,該後臺任務可能會更新UI線程中的某些值。如果用戶必須等待後臺操作完成,則可以顯示ProgressDialog並在OnPreExecute方法中阻止應用程序,然後將其隱藏在onPostExecute中。

正如我所說,請描述更多您的需求和目標,你想實現。