Android中的观察者模式

时间:2010-08-16 04:53:52

标签: android observer-pattern

我有一个问题。
我有两个主题:'工人'和'UI'线程 2.当工程师通知UI线程时,工作人员继续等待来自服务器的数据 3.在更新UI上显示屏幕上的Toast消息。

第3步是问题所在:

  

android.view.ViewRoot $ CalledFromWrongThreadException:只有   创建视图层次结构的原始线程可以触及其视图。

使用mHandler,runOnUIThread会减慢UI线程(UI显示webview),因为我必须不断检查来自服务器的数据。

3 个答案:

答案 0 :(得分: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...
    }
}

答案 1 :(得分:2)

我会使用服务,并将您的活动绑定到服务。然后,服务可以在有新数据时发送广播

答案 2 :(得分: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.