In Android, child threads cannot update ui.
So we need to dynamically change the ui view through other ways,
1、runOnUiThread
An ui-update method provided by activity, which requires the use of opening threads when Fragment needs to be used.
This method is the simplest and convenient to update some notifications that do not require judgment, such as dynamically obtaining the number of unread messages in a chat project.
runOnUiThread(new Runnable() { @Override public void run() { sendMessage("[Auto Reply]Hello, I'm a Robot"); } });
2、Handler message
Use this method to set the control of button countdown, which is also a relatively common method to update ui.
Create a main thread to receive messages continuously sent by the child thread, and determine the type of message passed.
Perform update operations of relevant ui according to the type.
Create threads for receiving:
private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch () { case 0: setResult(RESULT_OK); (); break; case 4: (false); ("Sent(" + (time) + ")"); break; case 5: (true); ("Reacquire verification code"); time = 10; break; } } };
Methods to send messages:
(5);
3、Handler Runnable
It also requires creating a thread first.
Handler handler = new Handler();
Set loading delay using postDelayed where it is loading at the beginning
(new Runnable() { @Override public void run() { updataData(); } }, 2000);
Or we want to perform an automatic refresh action, and when the action is completed, hide the refresh effect.
//Open a refresh thread (new Runnable() { @Override public void run() { //start (true); } }); // Listen to refresh status operation (new () { @Override public void onRefresh() { //Set delay refresh time 1500 (new Runnable() { @Override public void run() { //Refresh data updataData(); } }, 1800); } });
4、AsyncTask
AsyncTask makes it easier to use UI threads. This class allows for background operations and update views on UI threads without manipulating threads and handlers.
AsyncTask is designed as a helper class Thread, Handler and does not constitute a general threading framework. Used for short-term update operations.
When using it, you need to inherit AsyncTask and override the method:
doInBackground: used to return results
onProgressUpdate: onProgressUpdate is executed in a UI thread, and all operations can be performed on the UI space.
onPostExecute: Receive the return result of doInBackground, used to update the UI
class AsyncTaskWrapper extends AsyncTask<Void, Integer, Object>{ @Override protected Object doInBackground(Void... voids) { try { (2000); } catch (InterruptedException e) { (); } return null; } @Override protected void onProgressUpdate(Integer... values) { (values); ("Progress",valuse); } @Override protected void onPostExecute(Object o) { (o); ("Message",o); } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.