Android _ Reading Notes _ 1

Source: Internet
Author: User

Threads and asynchronous operations

This section describes the importance of asynchronous processing and when to use Asynchronous processing ......

Important:

1:

Introduction and example of the AsyncTask class ......

Inherit the AsyncTask class and implement its defined event methods to manage background operations.

It is very convenient that the AsyncTask class has already created a simple interface for asynchronous operations. We only need to implement this interface to implement asynchronous operations very quickly.

In addition, in the latest sdks, it can manage multiple tasks simultaneously through several physical kernels and an internal thread pool.

Including:

The onPreExecute () method runs on the UI thread before the background operation starts.

The doInBackground () method runs in the background and processes background operations.

The publishProgress () method can be called from this method to periodically notify the UI thread about the progress of background operations.

When its (doInBackground () method) calls the publishProgress () method

The onProgressUpdate () method runs in the UI thread and transmits different information through different parameters.

Once the background operation is completed, the onPostExrcute () method is automatically called in the UI thread. The AsyncTask class can process the operation in the future without blocking the UI thread.

There are two startup methods:

1. instantiate the created AsyncTask subclass and call the execute () method to start asynchronous operations.

2. instantiate the created AsyncTask subclass and call the executeOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR, Integer...) method to start asynchronous operations.

Difference: in devices with API L11 +, the former (execute () task can be executed in parallel on a multi-core processor device, this method can effectively improve the task completion speed and implicitly improve the efficiency and smoothness of applications. The latter (executeOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR, Integer...) ensures that several tasks are executed simultaneously, and each task is independent of each other.

Note: If you do not want to execute multiple tasks at the same time, you can call the executeOnExecutor (AsyncTask. SERIAL_EXECUTOR) method. However, it can be confirmed linear only in API L14 +.

Instance:

1 package com. example. asynctask; 2 3 import android. OS. asyncTask; 4 import android. OS. bundle; 5 import android. OS. systemClock; 6 import android. app. activity; 7 import android. widget. textView; 8 9 public class SimpleAsyncTask extends Activity {10 11 @ Override12 protected void onCreate (Bundle savedInstanceState) {13 super. onCreate (savedInstanceState); 14 setContentView (R. layout. activity_main); 15 16 Co UntingTask tsk = new CountingTask (); 17 tsk.exe cute (); 18 19} 20 21 private class CountingTask extends AsyncTask <Void, Integer, Integer> {22 23 CountingTask () {24} 25 26 @ Override27 protected Integer doInBackground (Void... unused) {28 29 int I = 0; 30 while (I <100) {31 32 SystemClock. sleep (100); 33 I ++; 34 35 if (I % 5 = 0) {36 37 // update UI38 publishProgress (I) Every 5% progress ); 39} 40} 41 42 return I; 43} 44 45 Protected void onProgressUpdate (Integer... progress) {46 47 TextView TV = (TextView) findViewById (R. id. text); 48 TV. setText (progress [0] + "% Complete! "); 49} 50 51 protected void onPostExecute (Integer result) {52 53 TextView TV = (TextView) findViewById (R. id. text); 54 TV. setText ("Count Complete! Count to "+ result. toString (); 55} 56} 57}Execute () implements 1 package com. example. asynctask; 2 3 import android. app. activity; 4 import android. OS. asyncTask; 5 import android. OS. bundle; 6 import android. OS. systemClock; 7 import android. widget. textView; 8 9 public class SimpleMultiCoreAsyncTask extends Activity {10 11 @ Override12 protected void onCreate (Bundle savedInstanceState) {13 super. onCreate (savedInstanceState); 14 setContentView (R. layout. ac Tivity_simple_multi_core_async_task); 15 16 CountingTask tsk = new CountingTask (); 17 tsk.exe cuteOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR, R. id. TV _AsyncTask_1); 18 19 startParallelTask (R. id. TV _AsyncTask_2); 20 startParallelTask (R. id. TV _AsyncTask_3); 21 startParallelTask (R. id. TV _AsyncTask_4); 22 startParallelTask (R. id. TV _AsyncTask_5); 23 startParallelTask (R. id. TV _AsyncTask_6); 24 25 // note that only The first five are started at the same time, and the first 6th will be started after the startup ...... 26} 27 28 private void startParallelTask (int _ id) {29 30 CountingTask tsk = new CountingTask (); 31 tsk.exe cuteOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR, _ id); 32} 33 34 private class CountingTask extends AsyncTask <Integer, Integer, Integer> {35 36 private int _ counterID; 37 38 CountingTask () {39} 40 41 @ Override42 protected Integer doInBackground (Integer... _ id) {43 44 _ CounterID = _ id [0]; 45 int I = 0; 46 47 while (I <100) {48 49 SystemClock. sleep (100); 50 I ++; 51 52 if (I % 5 = 0) {53 54 // update UI55 publishProgress (I) Every 5% progress ); 56} 57} 58 59 return I; 60} 61 62 protected void onProgressUpdate (Integer... progress) {63 64 TextView TV = (TextView) findViewById (_ counterID); 65 TV. setText (progress [0] + "% Complete! "); 66} 67 68 protected void onPostExecute (Integer result) {69 70 TextView TV = (TextView) findViewById (_ counterID); 71 TV. setText (" Count Complete! Count to "+ result. toString (); 72} 73} 74}ExecuteOnExecute () Implementation

 

------------------------------------------------ I am a split line --------------------------------------------------------------

 

2: Thread class

Compared with the above (AsyncTask), its (Thread) Class imports existing code more easily and directly

For an Activity class with independent threads that can manage the life cycle of a Thread, it generally includes a Handler type variable. When the Thread class is instantiated and started, the Handler post () the method will be used to communicate with the main UI thread. Of course, you can also use the runOnThread () method in the Activity class or the post () and postDelayed () methods in the View class () method to communicate with the main UI thread.

Instance:

1 package com. example. asynctask; 2 3 import android. OS. bundle; 4 import android. OS. systemClock; 5 import android. app. activity; 6 import android. view. menu; 7 import android. widget. textView; 8 9 public class SimpleThread extends Activity {10 11 @ Override12 protected void onCreate (Bundle savedInstanceState) {13 super. onCreate (savedInstanceState); 14 setContentView (R. layout. activity_simple_thread); 15 16 Final TextView TV _thread = (TextView) findViewById (R. id. TV _thread); 17 18 new Thread (new Runnable () {19 20 @ Override21 public void run () {22 23 int I = 0; 24 25 while (I <100) {26 27 SystemClock. sleep (250); 28 I ++; 29 30 final int curCount = I; 31 32 if (curCount % 5 = 0) {33 34 TV _thread.post (new Runnable () {35 36 @ Override37 public void run () {38 39 TV _thread.setText (curCount + "% Com Plete! "); 40} 41}); 42} 43} 44 45 TV _thread.post (new Runnable () {46 47 @ Override48 public void run () {49 50 TV _thread.setText (" Count Complete! "); 51} 52}); 53} 54}). start (); 55} 56}Thread () Implementation

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.