2010-08-16 77 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.