Please respect other people's labor results, reproduced please specify the source: Asynchronous specific explanation of Android development (i) Thread+handler
http://blog.csdn.net/fengyuzhengfan/article/details/40211589
There are often time-consuming operations such as file read-write, network access, and so on, which are not recommended for thread on the UI line in real-time Android development project.
So we're going to open a new thread. Take these time-consuming actions in a child thread. During the time-consuming operation. The UI often needs to be updated, but Android is different in that it is intended to change the UI in a child thread. So there is the thread+handler mechanism, thread to update the UI by sending messages and passing data through handler to the main thread. The following describes how to implement asynchronous operations in Thread+handler mode.
1. What is the handler message delivery mechanism?
When a program starts for the first time, Android will start a main thread (Mainthread) at the same time, and the main thread is responsible for handling UI-related events, such as user key events, User touch screen events, and screen drawing events, and distributing related events to the appropriate components for processing. So the main thread is often called the UI thread.
The Android messaging mechanism is also a form of "event handling" mechanism mainly to solve the multi-threaded problem of Android application--android platform just agree UI thread to change the UI component in activity, This causes the newly started thread to not dynamically change the property values of the interface component.
However, in the actual development of Android application, especially in the game development involving animation, it is necessary for the newly-launched thread to change the attribute value of the interface component periodically, which needs to be realized by means of handler's message passing mechanism.
2. Handler Class Brief Introduction
Handler The main functions of the class are two:
1) Send the message in the newly started thread.
2) Gets and processes the message in the main thread.
The above statement looks very easy and seems to be in two steps: Send a message in a newly-started thread. The message is then fetched and processed in the main thread. But this process involves a problem: when does a newly-started thread send a message? When does the main thread get and process messages? The timing is clearly not in control.
In order for the main thread to "timely" handle the messages sent by the newly-started thread, it is clear that only the callback can be implemented-we only have to rewrite the method of processing the message in the handler class, when the newly-started thread sends the message. The message is sent to the MessageQueue associated with it, and handler constantly fetches and processes the message from MessageQueue-which causes the method in the handler class to process the message to be recalled.
Handler class includes, for example, the following methods for sending, processing messages :
1) void Handlemessage (Message msg): Method for handling messages. The method is often used to be rewritten.
2) Final Boolean hasmessages (intwhat): Check whether the message queue includes a message that the What attribute is a value.
3) Final Boolean hasmessages (Intwhat, Object object): Check whether the message queue includes the message that the What property is the specified value and the object property is the specified objects.
4) Multiple overloads of Message Obtainmessage (): Get messages. Sendemptymessage (int): Sends an empty message.
5) Final booleansendemptymessagedelayed (int what, long Delaymillis): Specifies the number of milliseconds after which an empty message is sent.
6) Final booleansendmessage (message msg) to send the messages immediately.
7) Final booleansendmessagedelayed (Message msg, long Delaymillis): Specifies the number of milliseconds after which the message is sent.
With these methods, the program can easily use handler for message delivery.
3. Thread+handler Implementing an 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 android.widget.simpleadapter.viewbinder;/** * Get all software information * 1. Display all software in the system in an asynchronous manner * 2. Click to open the specified software * 3. Save the package name and activity name of all software locally sharedpreferences * @author JPH * date:2014.09.21 */public class ScanPackage1 extends Activity {/** Scan succeeded **/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,object>> (); Private Simpleadapter adapter;//obtain all installation software information private list<packageinfo> allpackageinfos;//get the software information installed by private List <PackageInfo> userpackageinfos;//obtains the system installs the software information private list<packageinfo> Syspackageinfos; Handler mhandler=new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubswitch (msg.what) {case flag_load_success://completed scanning break;case scanning://is scanning items.add ((map<string, object>) msg.obj); /Notification Adapter Data Change adapter.notifydatasetchanged (); 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);//viewbinder This class can help simpleadapter load pictures (e.g. 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.setimagedrawable ((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 (AR G2); Intent intent=new Intent (); Intent.setcomponent (New ComponentName (Pinfo.packagename, Pinfo.activities[0].name)) ; StartActivity (intent);} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}});} --------* Create a thread to load the installer *--------------*******************//private class Scanthread extends Thread { @Overridepublic void Run () {//Get system Install all software information Allpackageinfos = Getpackagemanager (). Getinstalledpackages ( packagemanager.get_uninstalled_packages| packagemanager.get_activities);//define User installation software information Package Userpackageinfos = new arraylist<packageinfo> ();// Define the system installation software information Package Syspackageinfos = new arraylist<packageinfo> ();//loop out all software information for (int i = 0; i < allpackageinfos.size ( ); i++) {//Get 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);} Gets the program's icon drawable Ico=scanpackage1.this.getpackagemanager (). Getapplicationicon (AppInfo);//Gets the name of the program string appname= (String) ScanPackage1.this.getPackageManager (). Getapplicationlabel (AppInfo); Map<string, Object>item=new hashmap<string, object> ();//Gets the package name of the program 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);}};/ * * To write information about the program installed in the system to the configuration file * @param syspackageinfos system installation Software information Package * @param userpackageinfos User install software packet */private void Saveinfo (Lis T<packageinfo> syspackageinfos,list<packageinfo> Userpackageinfos) {//Add user-installed software to the collection that is added to the system softwareSyspackageinfos.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 = Syspacka Geinfos.get (i). packagename;//Remove activity information activityinfo Activityinfo = Syspackageinfos.get (i). activities[0];// Remove the activity name string activityname=activityinfo.name;//write the program information to the configuration file editor.putstring (PackageName, activityname);} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}} Editor.commit ();}}
Code Analysis:
In the above code, the UI passes the code new Scanthread (). Start (); Initiates a thread to scan all packages. The child thread then passes the scan result through mhandler.sendmessage (message) and sends it to the UI thread at all times.
After the UI thread receives a message from the child thread, it gets the data that the message carries, and then updates to the ListView. This enables an asynchronous operation.
If you think this blog post is helpful to you, please give this blog a praise!
can also focus on Fengyuzhengfan's blog. Watch a lot of other wonderful!http://blog.csdn.net/fengyuzhengfan/
Asynchronous specific explanation of Android development (i) Thread+handler