Observer pattern in Android

早过忘川 提交于 2019-12-13 01:54:13

问题


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.

Step 3 is problem as it says:

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

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


回答1:


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

Here is good example http://www.screaming-penguin.com/node/7746

And here is official docs.

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



回答2:


I would use a service, and bind your activity to the service. Then the service can send a broadcast when it has new data




回答3:


Object Observer pattern in Android ?

Definition: The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

       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.


来源:https://stackoverflow.com/questions/3490674/observer-pattern-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!