Android中的观察者模式 [英] Observer pattern in Android

查看:388
本文介绍了Android中的观察者模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题.
1.我有两个线程:'worker'和'UI'线程.
2. Worker一直在等待来自服务器的数据,当它收到通知到UI线程时的数据.
3.在更新UI上,屏幕上显示Toast消息.

I have an issue.
1. I have two threads: 'worker' and 'UI' thread.
2. Worker keeps on waiting for data from server, when gets it notifies to UI thread.
3. On update UI shows Toast message on screen.

第3步是问题所在,因为它说:

Step 3 is problem as it says:

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

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

使用mHandler时,runOnUIThread会减慢UI线程的速度(UI显示Webview),因为我必须不断检查服务器中的数据.

Using mHandler, runOnUIThread slows down the UI thread (UI displays webview), as I have to continuously check for data from server.

推荐答案

使用AsyncTask来实现.覆盖doInBackground以获取数据(在单独的线程上执行),然后覆盖onPostExecute()以显示吐司(在UI线程上执行).

Use AsyncTask to implement this. Override doInBackground to get the data (it is executed on the separate thread), then override onPostExecute() to show the toast (it is executed on the UI thread).

这是一个很好的例子 http://www.screaming-penguin.com/node/7746

这是官方文档.

UPD:有关如何处理部分进度的示例.

UPD: Example on how to handle partial progress.

    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...
    }
}

这篇关于Android中的观察者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆