Method of Switching to Main Thread Execution in Android
- 2021-12-11 09:08:16
- OfStack
Method 1: view. post (Runnable runnable)
Using view object, calling post method can execute the code inside the main thread, and postDelayed is delayed execution, which can also achieve the same effect. For example:
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(" Update textView");
}
});
Method 2: runOnUiThread (Runnable runnable)
Call runOnUiThread directly in Acitivity or pass the context object of Activity to the child thread for call. For example:
runOnUiThread(new Runnable() {
public void run() {
textView.setText(" Update textView");
}
}
Method 3: handler. post (Runnable runnable)
If it is in the main thread, one Handler object can be directly obtained. If it is in the sub-thread, Looper and Queue of the main thread need to be obtained
// Main thread
Handler handler = new Handler();
// Sub-thread
Handler handler = new Handler(Looper.getMainLooper());
Then call the post method, or postAtTime, postAtDelayed. For example:
handler.post(new Runnable() {
@Override
public void run() {
textView.setText(" Update textView");
}
});
Method 4: handler. sendMessage (Message message)
This is a common way to send messages through sendMessage and then process them in handleMessage. For example:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// Processing messages
textView.setText(" Update textView" + msg);
switch(msg.what) {
case 0:
// Processing the specified message
break;
}
}
};
handler.sendEmptyMessage(0);
Method 5: Use AsynTask
AsyncTask asyncTask = new AsyncTask() {
@Override
protected Object doInBackground(Object[] objects) {
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
};
The doInBackground method executes in a child thread, and its return results are passed to the onPostExecute method, which runs on the main thread.