Android thread mechanism-AsyncTask and androidasynctask
For Android, why is multithreading used? Because after Android, Google stipulated that network operations cannot be executed in the main thread, and a multi-thread mechanism was established, A friend with learning experience in JAVA must know what multithreading means. Simply put, in a JAVA program, the main () function is enabled for the main thread of the program, in order to complete some time-consuming operations, we do not want to affect the execution of the main Thread. This is usually done by creating a subthread through the Thread object. Simply put, a program has only one main thread and can have multiple main threads. This is also true in the Android world. Android is a single-threaded model and time-consuming operations must be executed in non-main threads. Therefore, Google provides an AsyncTask multi-threaded operation object for us to facilitate the use of threads.
Pay special attention to the usage of Android threads. Android cannot update the UI in sub-threads. I believe many beginners must have encountered this problem. How can this problem be solved? In the Activity, we can use
New Thread (new Runnable () {@ Override public void run () {Log. v ("abc", "subthread execution"); runOnUiThread (new Runnable () {@ Override public void run () {Log. v ("abc", "main thread execution returned ");}});}}). start ();
However, in Fragement, runOnUiThread () cannot be used, so pay attention to it when using it. Of course, in Android, we can also use Handler + Messager to complete multi-threaded operations. For the usage here, I have already introduced it to you in my previous blog, so I will not repeat it here, next we will introduce the focus of this article: The use of AsyncTask.
AsyncTask <Parans, Progress, Result> is an abstract class. We need to implement this abstract class before using it. For its three parameters: Parans: The parameter type entered when the task is started; progress: Type of the return value during background task execution; Result: Type of the returned Result after the background task is completed.
Callback method for building AsyncTask subclass: 1. doInBackground: the task to be completed by the background thread must be rewritten asynchronously; 2. onPreExecute: called before the time-consuming operations on the background are executed, the user completes some initialization operations. 3. onPostExecute: After doInBackground () is completed, the system will automatically call it and pass the returned value after doInBackground () is executed to the onPostExecute () method, to put it simply, doInBackground () completes time-consuming operations and returns an onPostExecute () method to update the UI. 4. onProgressUpdate: In the doInBackground () method, call the publishProgress () method, this method is triggered when the task execution progress is updated.
After talking about this, I believe you still have some doubts. Here we will introduce the usage of AsyncTask through two simple Android applets:
A. AsyncTask is the execution sequence of abstract methods:
1. Create an AsyncTask subclass object:
public class MyAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); Log.v("abc", "onPreExecute"); } @Override protected Void doInBackground(Void... arg0) { Log.v("abc", "doInBackground"); publishProgress(arg0); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Log.v("abc", "onPostExecute"); } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); Log.v("abc", "onProgressUpdate"); }}
2. Call the MainActivity to the subthread for execution:
Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); new myasynctask(cmd.exe cute (); // start execution}
3. log printed after execution:
This log information solves your concerns. Let's look at an example of using AsyncTask to load network images.
B. Attach network images:
1. First, create an xml file that carries the Activity layout file:
<RelativeLayout 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:layout_margin="10dp" tools:context=".MainActivity" > <ImageView android:id="@+id/img" android:layout_width="match_parent" android:layout_height="match_parent" /> <ProgressBar android:id="@+id/progressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" android:layout_centerInParent="true" /></RelativeLayout>
The layout file is very simple. It is an ImageView + ProgressBar. When loading ImageView, we use ProgressBar to remind users to wait.
2. Create an Activity object:
public class AsyncTaskImager extends Activity { private ProgressBar pb; private ImageView image; private static final String url = "https://www.baidu.com/img/bdlogo.png"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.imager); init(); new ImageAsyncTask().execute(url); } private void init() { pb = (ProgressBar) findViewById(R.id.progressbar); image = (ImageView) findViewById(R.id.img); } class ImageAsyncTask extends AsyncTask<String, Void, Bitmap>{ @Override protected void onPreExecute() { super.onPreExecute(); pb.setVisibility(View.VISIBLE); } @Override protected Bitmap doInBackground(String... params) { Bitmap bitmap = null; URLConnection conn = null; String url = params[0]; try { conn = new URL(url).openConnection(); InputStream in = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); bitmap = BitmapFactory.decodeStream(bis); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); pb.setVisibility(View.GONE); image.setImageBitmap(result); } } }
At this point, our major achievements have been basically completed. Do not forget to make a declaration in AndroidManifest. xml.
3. Add Network Operation permissions:
<uses-permission android:name="android.permission.INTERNET"/>
Because we need to use the network connection, we need to add a network access permission in AndroidManifest. xml.
4. Configure the last running result:
The introduction of AsyncTask can end up. If you have any questions, please leave a message to discuss it. I am welcome to criticize and give some advice on my understanding. Thank you.