Android watcher pattern

I have a problem.
1. I have two streams: the stream "worker" and "UI".
2. The employee continues to wait for data from the server when it receives a notification about the user interface stream.
3. The Toast message appears on the screen in the UI update window.

Step 3 is a problem as it says:

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

Using mHandler, runOnUIThread slows down the user interface thread (the user interface displays a web view), since I have to constantly check the data from the server.

+1
source share
3 answers

Use AsyncTask to implement this. Override doInBackground to receive the data (executed in a separate thread), then override onPostExecute () to show the toast (it runs in the user interface thread).

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

And here are the official documents .

UPD: An example of 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
source

I would use the service and tie your activities to the service. The service can then send the broadcast when it has new data.

+2
source

Observer Android?

Definition: An observer pattern defines a one-to-many relationship between objects, so when one object changes state, all 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.
+1
source

Source: https://habr.com/ru/post/1761291/


All Articles