Android development and learning path-asynchronous Message Handler, Message, logoff, and AsyncTask
In the simple music player, Handler is used, and there has not been much research and learning. Here we will learn about the asynchronous message processing mechanism in android. Handler is used here mainly because the UI cannot be updated in the thread, but it can only be updated through Handler. There are several concepts about asynchronous message processing.
1. Message: The data unit for inter-thread communication. For example, if you want to download a song in the background and update the ui after the song is downloaded, you can send a Message containing the updated information to the UI thread.
2. MessageQueue: Message Queue, used to store all messages published through Handler. Because it is a queue, it is first-in-first-out.
3. Handler: the main processor of the Message. It is responsible for adding the Message to the Message queue and processing the Message in the Message queue.
4. Logoff: cyclically manage MessageQueue, cyclically retrieve the Message in MessageQueue, and hand it to the corresponding Handler for processing.
5. thread: the UI thread is the main thread, and a MessageQueue will be created for the android Startup Program. Each thread can contain a loose object and a MessageQueue data structure.
Let's take an example below. Create a new project HandlerTest and write a simple layout as follows:
<! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical" android: layout_margin = "10dp" tools: context = "com. example. jared. handlertest. mainActivity "> <edittext android Oid: id = "@ + id/inputContent" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: hint = "Enter the content to be changed"> <button android: id = "@ + id/changeViewContent" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "Change The ViewContent" android: textallcaps = "false"> <textview android: id = "@ + id/testHandler" android: text = "I am old !!! "Android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_margin =" 20dp "android: textsize =" 22dip "android: layout_gravity = "center"> </textview> </button> </edittext> </linearlayout>
Enter the content here and press the button to change the content of the TextView. Compile the MainActivity Code as follows:
package com.example.jared.handlertest;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends AppCompatActivity { public static final int UPDATA_VIEW = 1; private TextView textView; private Button changeContent; private EditText inputContent; private Thread mThread; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATA_VIEW: String mInputContent = inputContent.getText().toString(); textView.setText(mInputContent); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.testHandler); inputContent = (EditText)findViewById(R.id.inputContent); changeContent = (Button)findViewById(R.id.changeViewContent); changeContent.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.changeViewContent: mThread = new Thread(runnable); mThread.start(); break; default: break; } } } Runnable runnable = new Runnable() { @Override public void run() { Message message = new Message(); message.what = UPDATA_VIEW; mHandler.sendMessage(message); } };}
Here, a new Handler is created. The handleMessage method processes the sent Message. The Thread sends the message and updates the TextView content. Run the following command:
The basic Handler has been completed. Next we will learn about AsyncTask.
AsyncTask is a helper class that facilitates the compilation of background threads and UI threads. Its internal implementation is a thread pool, and each background will be submitted to the thread pool for execution. AsyncTask has three template functions:
1. Params: parameter type passed to the background task.
2. Progress: the unit type of Progress during background computing execution.
3. Result: Type of the Result returned by the background execution.
You only need to use Void to indicate the type you do not need.
AsyncTask needs to rewrite five methods:
1. onPreExecute method: Prepare to run. The callback function is called by the UI thread immediately after the task is executed. Generally, a progress bar is displayed.
2. doInBackground (Params ...) method: It is running in the background. Generally, the time-consuming background computing is executed here. The calculation result is returned to the function. If the third parameter of AsyncTask is Void, no response is required. The UI cannot be updated here, however, you can call publishProgress (Progress ...) method.
3. onProgressUpdate (Progress...) method: Progress Update. The UI thread is called after the publishProgress (Progress...) method is called. Generally, a Progress is displayed dynamically.
4. onPostExecute (Result) method: After the background task is completed, the system returns the Result. You can perform some UI operations, such as reminding the task execution Result and closing the progress bar dialog box.
5. onCancelled method: cancels a task and calls the cancel () method of AsyncTask.
In the following example, the Handler code is not deleted using AsyncTask. The Code is as follows:
package com.example.jared.handlertest;import android.os.AsyncTask;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends AppCompatActivity { public static final int UPDATA_VIEW = 1; private TextView textView; private Button changeContent; private EditText inputContent; private Thread mThread; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATA_VIEW: String mInputContent = inputContent.getText().toString(); textView.setText(mInputContent); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.testHandler); inputContent = (EditText)findViewById(R.id.inputContent); changeContent = (Button)findViewById(R.id.changeViewContent); changeContent.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.changeViewContent: // mThread = new Thread(runnable); // mThread.start(); changeViewContentTask task = new changeViewContentTask(); task.execute(); break; default: break; } } } class changeViewContentTask extends AsyncTask
{ @Override protected Boolean doInBackground(Void... voids) { return null; } @Override protected void onProgressUpdate(Integer... values) { } @Override protected void onPostExecute(Boolean b) { String mInputContent = inputContent.getText().toString(); textView.setText(mInputContent); } @Override protected void onPreExecute() { } @Override protected void onCancelled() { } } Runnable runnable = new Runnable() { @Override public void run() { Message message = new Message(); message.what = UPDATA_VIEW; mHandler.sendMessage(message); } };}
In this case, define a task, and then task.exe cute (); then you can execute the task. If the effect is shown above, no image is added.