Asynchronous explanation of Android development (1) Thread + Handler and androidhandler

Source: Internet
Author: User

Asynchronous explanation of Android development (1) Thread + Handler and androidhandler

Please respect others' labor achievements. Reprinted with the source: asynchronous explanation of Android development (1) Thread + Handler

Http://blog.csdn.net/fengyuzhengfan/article/details/40211589

In actual Android development projects, time-consuming operations such as file read/write and network access are often performed. These time-consuming operations are not recommended in the UI thread. Therefore, we will open a new thread to perform these time-consuming operations in the Child thread. During time-consuming operations, the UI often needs to be updated, but Android does not allow UI modification in the Child thread. Therefore, the Thread + Handler mechanism emerged. The Thread sends messages and transmits data to the main Thread through handler to update the UI. The following describes how to implement asynchronous operations through Thread + Handler.


1. What is the Handler message transmission mechanism?

When a program is started for the first time, Android will start a main thread at the same time. The main thread is mainly responsible for processing UI-related events, for example, the user's key event, the user's touch screen event, and the screen drawing event, and relevant events are distributed to the corresponding components for processing. Therefore, the main thread is often called the UI thread.

The message passing mechanism of Android is another form of "event processing". This mechanism is mainly used to solve the multithreading problem of Android applications. The Android platform only allows the UI thread to modify the UI components in the Activity, this will make the newly started thread unable to dynamically change the attribute value of the interface component. However, in actual Android Application Development, especially in game development involving animation, You need to enable the newly started thread to periodically change the attribute values of interface components, therefore, the Handler message transmission mechanism is required.

 

2. Introduction to the Handler class


The Handler class has two main functions:

1) send messages in the newly started thread.

2) obtain and process messages in the main thread.

 

The above statement seems very simple, as long as it can be divided into two steps: Send a message in the newly started thread, and then get and process the message in the main thread. But this process involves a question: when will the newly started thread send messages? When will the main thread obtain and process messages? This time is obviously difficult to control.

In order to make the main thread "timely" handle the messages sent by the newly started thread, it is clear that it can only be implemented through callback-we only need to override the method for processing messages in the Handler class, when a new thread sends a message, the message is sent to the associated MessageQueue, handler continuously obtains and processes messages from MessageQueue, which calls back the method for processing messages in the Handler class.

The Handler class contains the following methods for sending and processing messages:

1) void handleMessage (Message msg): method for processing messages. This method is usually used for rewriting.

2) final boolean hasMessages (intwhat): checks whether the queue contains messages with the value of what.

3) final boolean hasMessages (intwhat, Object object): checks whether the queue contains messages with the "what" attribute as the specified value and the "object" attribute as the specified Object.

4) Multiple overloaded Message obtainMessage (): gets the Message. SendEmptyMessage (int what): sends an empty message.

5) final booleansendEmptyMessageDelayed (int what, long delayMillis): specify how many milliseconds later to send an empty message.

6) final booleansendMessage (Message msg) sends the Message immediately.

7) final booleansendMessageDelayed (Message msg, long delayMillis): specify the number of milliseconds to send messages.

With the above methods, the program can easily use Handler to transmit messages.

 

3. Thread + Handler Implement Asynchronous Operation instance

 

Package com. jph. sp; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. app. activity; import android. content. componentName; import android. content. intent; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; import android. content. pm. ActivityInfo; import android. content. pm. applicationInfo; import android. content. pm. packageInfo; import android. content. pm. packageManager; import android. graphics. drawable. drawable; import android. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. imageView; import android. widget. listView; import android. widget. simpleAdapter; import andro Id. widget. simpleAdapter. viewBinder;/*** get all software information * 1. display All software in the system in asynchronous mode * 2. click Open specified software * 3. local SharedPreferences * @ author jph * Date: 2014.09.21 */public class ScanPackage1 extends Activity {/** scan successful **/private final static int FLAG_LOAD_SUCCESS = 0x10001; private final static int SCANNING = 0x10002; private ListView list; private List <Map <String, Object> items = new ArrayList <Map <String, Obje Ct> (); private SimpleAdapter adapter; // obtain all installed software information: private List <PackageInfo> allPackageInfos; // obtain the installed software information: private List <PackageInfo> userPackageInfos; // obtain the software information installed in the system. private List <PackageInfo> sysPackageInfos; Handler mHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubswitch (msg. what) {case FLAG_LOAD_SUCCESS: // scan break; case SCANNING: // SCANNING items. a Dd (Map <String, Object>) msg. obj); // notify the adapter to change the adapter data. yydatasetchanged (); break; default: break ;}};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. sp_layout); list = (ListView) findViewById (R. id. list); new ScanThread (). start (); adapter = new SimpleAdapter (this, items, R. layout. line, new String [] {"imgIco", "appName", "packageName"}, new Int [] {R. id. imgIco, R. id. tvAppName, R. id. tvAppDesc}); list. setAdapter (adapter); // The ViewBinder class can help SimpleAdapter load the image (for example, Bitmap, Drawable) adapter. setViewBinder (new ViewBinder () {@ Overridepublic boolean setViewValue (View view, Object data, String textRepresentation) {// TODO Auto-generated method stub if (view instanceof ImageView & data instanceof Drawable) {ImageView iv = (ImageView) view; iv. setImageDraw Able (Drawable) data); return true;} else {return false ;}}); list. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView <?> Arg0, View arg1, int arg2, long arg3) {// TODO Auto-generated method stubtry {PackageInfo pInfo = allPackageInfos. get (arg2); Intent intent = new Intent (); intent. setComponent (new ComponentName (pInfo. packageName, pInfo. activities [0]. name); startActivity (intent);} catch (Exception e) {// TODO: handle has tione. printStackTrace ();}}});} // *************** -------- * Create a thread to load the installer *--------------************* ***** * // Private class ScanThread extends Thread {@ Overridepublic void run () {// obtain information about all software installed in the system allPackageInfos = getPackageManager (). getInstalledPackages (PackageManager. GET_UNINSTALLED_PACKAGES | PackageManager. GET_ACTIVITIES); // defines the user's Installation Software Package userPackageInfos = new ArrayList <PackageInfo> (); // defines the system installation software package sysPackageInfos = new ArrayList <PackageInfo> (); // cyclically retrieve all software information for (int I = 0; I <allPackageInfos. size (); I + +) {// Obtain each software information PackageInfo temp = allPackageInfos. get (I); ApplicationInfo appInfo = temp. applicationInfo; if (appInfo. flags & ApplicationInfo. FLAG_UPDATED_SYSTEM_APP )! = 0 | (appInfo. flags & ApplicationInfo. FLAG_SYSTEM )! = 0) {// System Software sysPackageInfos. add (temp);} else {// The user installs the software userPackageInfos. add (temp);} // obtain the program icon Drawable ico = ScanPackage1.this. getPackageManager (). getApplicationIcon (appInfo); // obtain the program name String appName = (String) ScanPackage1.this. getPackageManager (). getApplicationLabel (appInfo); Map <String, Object> item = new HashMap <String, Object> (); // obtain the program package name String packageName = appInfo. packageName; item. put ("imgIco", ico); item. put ("appName", appName); item. put ("packageName", packageName); Message message = new Message (); message. what = SCANNING; message. obj = item; mHandler. sendMessage (message);} saveInfo (sysPackageInfos, userPackageInfos); mHandler. sendEmptyMessage (FLAG_LOAD_SUCCESS );}}; /*** write information about programs installed in the system to the configuration file * @ param sysPackageInfos System Installation Software Package * @ param userPackageInfos user installation software package */private void saveInfo (List <PackageInfo> sysPackageInfos, list <PackageInfo> userPackageInfos) {// Add the software installed by the user to the sysPackageInfos collection added to the system software. addAll (userPackageInfos); SharedPreferences sp = this. getSharedPreferences ("appInfs", MODE_PRIVATE); Editor editor = sp. edit (); for (int I = 0; I <sysPackageInfos. size (); I ++) {try {// get the package name of the program String packageName = sysPackageInfos. get (I ). packageName; // retrieves activity information ActivityInfo activityInfo = sysPackageInfos. get (I ). activities [0]; // retrieve activity name String activityName = activityInfo. name; // write program information to the configuration file editor. putString (packageName, activityName);} catch (Exception e) {// TODO: handle effectione. printStackTrace () ;}} editor. commit ();}}

 

Code Analysis:

In the code above, the UI passes the Code new ScanThread (). start (); start a sub-thread to scan all software packages, and then the sub-thread will scan the results through mHandler. sendMessage (message); always sent to the UI thread. After receiving a message from the subthread, the UI thread obtains the data carried by the message and updates it to the ListView. In this way, asynchronous operations are implemented.

If you think this blog post is helpful to you, please give it a compliment! You can also follow fengyuzhengfan's blog to learn more! Http://blog.csdn.net/fengyuzhengfan/

 


How to Use Android handler thread

Handler is equivalent to a thread stack, first processing, and using post to push the thread forward. One by one. That's simple.

How to Use android Thread and Handler

There is a problem with the way I write it. I should not remove the time-consuming data operations from handler, and put the time-consuming operations directly in new Thread, this new thread completes the last step to send handler. sendMessage (message) tells handler what to do to update the UI, and then only updates the UI in Handler. Thank you very much for the number of people upstairs ~
 

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.