Please respect other people's labor results, reproduced please specify the source: Asynchronous walkthrough of Android Development (i) Thread+handler
http://blog.csdn.net/fengyuzhengfan/article/details/40211589
Some time-consuming operations, such as file reads and writes, access to the network, are often performed in the actual Android development project, and these time-consuming operations are not recommended for thread on the UI line. So we're going to open a new thread, take these time-consuming actions in the child threads, the UI often needs to be updated during the time-consuming operation, but Android doesn't allow the UI to be modified 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 is launched for the first time, Android starts a main thread (Mainthread) at the same time, and the main thread handles UI-related events such as user key events, User touch screen events, and screen drawing events, and distributes related events to the corresponding components for processing. So the main thread is often called the UI thread.
The Android messaging mechanism is another form of "event handling" mechanism designed primarily to address the multithreaded problem of Android applications--android platform only allows UI threads to modify the UI components in the 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 to let the newly-launched thread change the attribute value of the interface component periodically, which needs to be realized by using the handler message passing mechanism.
2. Introduction to the Handler class
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 simple, as if it were a two-step process: Sending a message in a newly-started thread, and then fetching and processing the message in the main threads. 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 the callback is the only way to do it-we simply rewrite the method of handling the message in the handler class, and when the newly-started thread sends the message, the message is sent to the MessageQueue associated with it. The handler will constantly fetch and process messages from the MessageQueue-this will cause the method to process the message in the handler class to be recalled.
Handler class contains the following methods for sending and processing messages :
1) void Handlemessage (Message msg): Method for handling messages. This method is typically used to be overridden.
2) Final Boolean hasmessages (intwhat): Check whether the message queue contains a message that the What attribute is a value.
3) Final Boolean hasmessages (Intwhat, Object object): Checks whether the message queue contains 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) immediately sends messages.
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 you installed 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://complete scan 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 (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.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 (arg2); I Ntent intent=new Intent (); Intent.setcomponent (New ComponentName (Pinfo.packagename, pinfo.activities[0].name)); StartActivity (intent);} catch (ExceptIon e) {//Todo:handle exceptione.printstacktrace ();}});} --------* Create a line loads-mount 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 software Syspackageinfos.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 Activity name string activityname= activityinfo.name;//writes 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 subroutine to scan all packages, and then the child thread sends the scan results through mhandler.sendmessage (message); 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! You can also pay attention to Fengyuzhengfan's blog, watch more wonderful!http://blog.csdn.net/fengyuzhengfan/
Asynchronous walkthrough of Android Development (i) Thread+handler