2010-08-16 79 views
1

我遇到問題。
1.我有兩個線程:'worker'和'UI'線程。
2.工作人員一直等待來自服務器的數據,當它通知UI線程時。
3.在更新UI上,在屏幕上顯示Toast消息。Android中的觀察者模式

第三步是問題,因爲它說:

android.view.ViewRoot $ CalledFromWrongThreadException:只有創建視圖層次可以觸摸的意見 原來的線程。

使用mHandler,runOnUIThread減慢UI線程(UI顯示webview),因爲我不得不從服務器檢查數據。

回答

2

使用AsyncTask來實現這一點。重寫doInBackground以獲取數據(它在單獨的線程上執行),然後重寫onPostExecute()以顯示Toast(它在UI線程上執行)。

這裏是很好的例子http://www.screaming-penguin.com/node/7746

這裏是official docs

UPD:關於如何處理部分進度的示例。

class ExampleTask extends AsyncTask<String, String, String>{ 

    @Override 
    protected String doInBackground(String... params) { 
     while(true){ 
      //Some logic on data recieve.. 
      this.publishProgress("Some progress"); 
      //seee if need to stop the thread. 
      boolean stop = true; 
      if(stop){ 
       break; 
      } 
     } 
     return "Result"; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     super.onProgressUpdate(values); 
     //UI tasks on particular progress... 
    } 
} 
+0

感謝您的回覆, 實際上數據一直在來自服務器的某個時間間隔內,並且我必須更新UI。在這個例子中,我猜doInbackground只在單擊按鈕時執行,但在我的情況下,某人(線程)應始終準備好接收來自服務器的數據並傳遞給UI以更新自身。同時UI sud正常工作(webview).... – Placidnick 2010-08-16 09:04:12

+0

你可以在每次獲得另一部分數據時調用publishProgress。查看更新後的答案。 – 2010-08-16 09:17:55

+0

ohhh哇......我是你的大牌粉絲:) 康斯坦丁岩石! 謝謝。 – Placidnick 2010-08-16 10:54:26

2

我會使用服務,並將您的活動綁定到服務。然後服務可以發送廣播時,它有新的數據

+0

你可以請建議我示例代碼或一些參考,這將是對我有幫助。由於我必須實現聊天 1。如果用戶在另一個活動並回到聊天活動,他應該得到更新的聊天。 – Placidnick 2010-08-19 09:10:52

1

Android中的對象觀察者模式?

定義:觀察者模式定義的對象,這樣,當一個對象改變狀態時,它的所有受撫養人被通知和自動更新之間的一對多的依賴關係。

 The objects which are watching the state changes are called observer. Alternatively observer are also called listener. The object which is being watched is called subject. 

Example: View A is the subject. View A displays the temperature of a  container. View B display a green light is the temperature is above 20 degree Celsius. Therefore View B registers itself as a Listener to View A. If the temperature of View A is changed an event is triggered. That is event is send to all registered listeners in this example View B. View B receives the changed data and can adjust his display. 

Evaluation: The subject can registered an unlimited number of observers. If a new listener should register at the subject no code change in the subject is necessary.