“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Use the runOnUiThread () method

It is essentially an interface encapsulation of asynchronous message processing

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt_button = (Button) findViewById(R.id.button); tv_text = (TextView) findViewById(R.id.textView); bt_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // runOnUiThread(new Runnable() {@override public void run() {tv_text.settext (" I love China "); }}); }}); }Copy the code
new Thread(){ @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) {e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); button_led1.performClick(); Thread.sleep(1000); button_led2.performClick(); Thread.sleep(1000); button_led3.performClick(); Thread.sleep(1000); button_led4.performClick(); } } catch (InterruptedException e) { e.printStackTrace(); }}}); } }.start();Copy the code

Second, use Handler

Sends a message to the Handler. When the Handler receives the message, it performs the corresponding operation in the Handler.

  • Create a new Handel

    • Receives the parameters sent by the button
    • Modify the UI in the main thread
private static final int UPDATE_TEXT = 1; TextView tv_text; Private Handler Handler = new Handler() {public void Handler() {public void Handler() HandleMessage (Message MSG) {switch (MSG. What) {case UPDATE_TEXT: tv_text.settext (" big smart "); break; }}}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt_button = (Button) findViewById(R.id.button); tv_text = (TextView) findViewById(R.id.textView); Bt_button. SetOnClickListener (new View. An OnClickListener () {@ Override public void onClick (View v) {/ / create a new thread Thread(new Runnable() { @Override public void run() { Message message = new Message(); message.what = UPDATE_TEXT; SendMessage (Message); // Send the Message object handler.sendMessage(Message); } }).start(); }}); }Copy the code

Use AsyncTask

Create a new inner class in MainActivity that inherits the AsuncTask class and overrides the AsyncTask inner method.

The three construction parameters of AsyncTask are:

  • Params is the parameter passed in
  • Progress Displays the specified generic type as the return value type
  • Result Indicates the returned value after the task is executed

Among them are:

protected void onPreExecute()

A method executed before starting a task is used to initialize some interface, such as displaying a progress bar dialog box

Boolean doInBackground(Void… voids)

Methods executed at the start of a task perform time-consuming operations, and return the result via a return statement if the AsyncTask task has completed. Void does not return the result. UI operations cannot be performed in this method if needed, call publishProgress (Progress…) Method and after calling this method the onProgressUpdate will get executed

After calling the publishProgress method in doInBackground, onProgressUpdate will get the parameters that are carried out in the execution method that are passed in the background task summary to operate on the uI in this method

protected void onProgressUpdate(Integer… values)

This method is called soon after the task has finished executing and is returned by a return statement. Use the returned data for UI operations. For example, remind task execution result. And close the progress bar dialog box.

public class MainActivity extends AppCompatActivity { TextView tv1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt_thread = (Button) findViewById(R.id.button); tv1 = (TextView) findViewById(R.id.textView); bt_thread.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() {@override public void run() {// Start the DownloadTask task new DownloadTask().execute(); } }).start(); }}); } class DownloadTask extends AsyncTask<Void, Integer, Boolean> {@override protected void onPreExecute() {// A method used before starting a task // for some interface initialization, For example, display a progress bar dialog box log.d ("MainActivity", "onPostExecute: I'm going to start "); } @Override protected Boolean doInBackground(Void... Voids) {// The method performed at the beginning of the task // Performs a time-consuming operation, returns the result via a return statement if the AsyncTask task has completed and does not return the result if void. // Cannot perform UI operations in this method. If necessary, call publishProgress (Progress...) Log.d("MainActivity", "doInBackground: I'm busy, I'm busy, I'm busy "); // After calling this method onProgressUpdate is executed publishProgress(); return null; } // After calling the publishProgress method in doInBackground, OnProgressUpdate gets the parameters that are passed in the background task summary to execute the method. In this method, the uI is operated on. Values) {log. d("MainActivity", "onProgressUpdate: I'm busy too "); Tv1. SetText (" hide "); super.onProgressUpdate(values); } // This method is called shortly after the task has completed and is returned by a return statement. Use the returned data for UI operations. For example, remind task execution result. And close the progress bar dialog box. @override protected void onPostExecute(Boolean aBoolean) {log. d("MainActivity", "onPostExecute: I'm done "); }}}Copy the code

StartForground () Foreground service

Starting threads in a service is finally closed with stopself ().

The IntentService stops automatically after the execution is complete