Several Ways to Update UI Views Using Asynchronous Threads in Android

Keywords: Android Fragment

In Android, a neutron thread cannot update the ui.

So we need to dynamically change ui views in other ways.

1,runOnUiThread

activity provides a lightweight way to update the ui, using getActivity.runOnUiThread to open threads when Fragment needs to be used
This method is the simplest, easy to update some notifications that need not be judged, such as dynamic acquisition of unread messages in chat items.

       runOnUiThread(new Runnable() {
            @Override
            public void run() {
                    sendMessage("[Automatic recovery]Hello, I'm a robot.");
              
            }

        });

2,Handler message

This method can be used to set up control such as button countdown, and it is also a common way to update the ui.

Create a main thread to receive messages sent continuously by sub-threads, and determine the type of message delivered by msg.what.
Update the ui according to the type.

Create threads to receive:

 private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    setResult(RESULT_OK);
                    TimerButtonActivity.this.finish();
                    break;
                case 4:
                    mTimer1.setEnabled(false);
                    mTimer1.setText("has been sent(" + String.valueOf(time) + ")");
                    break;
                case 5:
                    mTimer1.setEnabled(true);
                    mTimer1.setText("Retrieve the authentication code");
                    time = 10;
                    break;
            }

        }
    };

Method of sending message:

mHandler.sendEmptyMessage(5);

3,Handler Runnable

It is also necessary to create a thread first.

    Handler handler = new Handler();

Use postDelayed to set the load delay at the beginning of the load

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                updataData();
            }
        }, 2000);

Or we need to do an automatic refresh action to hide the refresh effect when the action is completed.

 //Open a refresh thread
        mFragmentMainRf.post(new Runnable() {
            @Override
            public void run() {
                //start
                mFragmentMainRf.setRefreshing(true);
            }
        });
        //Monitor refresh status operation
        mFragmentMainRf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //Setting Delayed Refresh Time 1500
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //refresh data
                        updataData();
                    }
                }, 1800);
            }
        });

4,AsyncTask

AsyncTask makes it easier to use UI threads. This class allows background operations to be performed and views to be updated on UI threads without manipulating threads and handlers.
AsyncTask is designed as an auxiliary class Thread, Handler and does not constitute a general threading framework. Used for short update operation.
When using it, you need to inherit AsyncTask and rewrite the method:
doInBackground: Used to return results
OnProgressUpdate: onProgressUpdate is executed in UI threads, all of which can operate on UI space
onPostExecute: Receives the return result of doInBackground for updating the UI

  class AsyncTaskWrapper extends AsyncTask<Void, Integer, Object>{

        @Override
        protected Object doInBackground(Void... voids) {
            try {
                Thread.sleep(2000);
                  } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.e("Progress",valuse);
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            Log.e("Message",o);
        }
    }

Posted by richei on Sat, 01 Jun 2019 11:29:28 -0700