Android Sina Weibo development (5) handler usage, Android multi-thread programming

Source: Internet
Author: User
Tags oauth
1. Functions of handler in Android

See how the SDK introduces it:

A handler allows you to send and process the message and thread's messagequeue runnable object. Each handler instance is related to a separate thread and the message queue of the thread. When you create a new handler, it is bound to the thread/Message Queue that creates it-from this point, it will provide the message and runnable to the message queue, and execute it when they come out of the message queue.

Handler has two main purposes: (1) delay messages and runnable, and execution at a certain point in the future; (2) queuing an action to be executed in other queues.

Scheduled messages are related to the following methods: Post (runnable), postattime (runnable, long), postdelayed (runnable, long), sendemptymessage (INT), sendmessage (Message ), sendmessageattime (message, long ),
And sendmessagedelayed (message, long ). Methods Starting with post can queue runnable objects to message queues. Methods Starting with sendmessage will contain messages of bundle data) the Chinese law is handled.

When posting or sending is sent to the processing program, you can make it run as soon as possible when the message queue is ready, or specify an absolute delay or processing time before it is executed. The last two enable timeouts, ticks, and other time series-based behaviors.

When an application creates a process, its main thread maintains a message queue, specifically used to run the application objects (activity, broadcast, etc.) at the top level of management and any windows they create. You can create your own thread and communicate with the main application thread through handler. This is the same as before, using the sendmessage function method, but from your new thread. Then, the runnable or message will be queued into the message queue and processed as appropriate.

The translation is not easy to understand. The explanation is as follows:

Android also has message queues and message loops. However, the message queues and message loops in Android are for specific threads. Messages in specific threads can only be distributed to this thread and cannot be transferred across threads, cross-process communication. Handler adds messages to a specific message queue and distributes and processes messages in the queue.

As can be seen from the SDK above, Handler has two functions: processing the message queue of the planned thread, such as adding some latency or processing the message with Bundle data, the message is processed in the handlemessage in handler. The second function is to communicate with the activity thread, that is, the UI thread. The sendmessage method is used, but called in the work thread created by the user.

2. Place the method for retrieving Weibo data in other threads.

In order not to cause ANR exceptions because the main thread is blocked for too long, you should (1) create a handler object in the main thread and rewrite its handlemessage method; (2) put network operations in another thread; (3) after processing, get the handler object of the main thread, create a message object, then sendmessage, and process it in handlemessage.

The changed hometimelineactivity. Java is as follows:

Package masofeng. zwd; import Java. util. arraylist; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import weibo4android. status; import weibo4android. user; import weibo4android. weibo; import weibo4android. weiboexception; import weibo4android. androidexamples. oauthconstant; import weibo4android. HTTP. accesstoken; import weibo4android. HTTP. requesttoken; import android. app. activity; import Android. app. listactivity; import android. content. context; import android.net. uri; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. widget. adapterview; import android. widget. baseadapter; import android. widget. button; import android. widget. imageview; I Mport android. widget. linearlayout; import android. widget. listview; import android. widget. simpleadapter; import android. widget. textview; import android. widget. adapterview. onitemclicklistener; import android. widget. adapterview. onitemlongclicklistener; public class hometimelineactivity extends listactivity implements onitemclicklistener, onitemlongclicklistener {private listview lv; private mylistadpter MLA; P Rivate list <status> homestatlsit; private Weibo; Private Static final int refresh_status = 1; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. hometimelinetab); system. setproperty ("weibo4j. oauth. consumerkey ", Weibo. consumer_key); system. setproperty ("weibo4j. oauth. consumersecret ", Weibo. consumer_secret); // create a requesttoken requ Esttoken requesttoken = new requesttoken ("1364680900", "token"); // create an accesstokenaccesstoken accesstoken = new accesstoken ("token", "token "); // set requesttoken and accesstoken to oauthconstant in the oauthconstant Singleton. getinstance (). setrequesttoken (requesttoken); oauthconstant. getinstance (). setaccesstoken (accesstoken); Weibo = oauthconstan T. getinstance (). getweibo (); Weibo. settoken (oauthconstant. getinstance (). gettoken (), oauthconstant. getinstance (). gettokensecret (); Lv = getlistview (); LV. setonitemclicklistener (this); LV. setonitemlongclicklistener (this); New mythread (). start () ;}// create a new handler class to receive messages from the worker thread to update uiprivate handler myhandler = new handler () {@ overridepublic void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. W Hat) {// update uicase refresh_status: MLA = new mylistadpter (hometimelineactivity. this, homestatlsit); LV. setadapter (MLA); break ;}}; // create a thread internal class for network operations class mythread extends thread {@ overridepublic void run () {try {// obtain the Weibo data homestatlsit = Weibo. getfriendstimeline (); // get the messagemessage MSG = myhandler of the handler in the main thread. obtainmessage (); // sets the Message Parameter MSG. what = refresh_status; // send the message to the main thread myhandler. sendmess Age (MSG);} catch (weiboexception e) {e. printstacktrace () ;}}@ overridepublic Boolean onitemlongclick (adapterview <?> Arg0, view arg1, int arg2, long arg3) {// arg2 is the position in the listview, and arg3 is the value log returned by getitemid. I ("myweibo", "onitemlongclick ---> arg2:" + arg2 + "; arg3:" + arg3); Return false ;}@ overridepublic void onitemclick (adapterview <?> Arg0, view arg1, int arg2, long arg3) {// arg2 is the position in the listview, and arg3 is the value log returned by getitemid. I ("myweibo", "onitemclick ---> arg2:" + arg2 + "; arg3:" + arg3 );}} // class mylistadpter extends baseadapter {private context CTX; private list <status> adplist; private layoutinflater Inflater; // custom constructor used for listview listeners, to obtain listpublic mylistadpter (context ctx1, list <status> List) {super (); adplist = List; this. CTX = ctx1; Inflater = layo Utinflater. From (CTX); log. I ("myweibo", "listadpter ---> construct! ") ;}@ Overridepublic int getcount () {log. I ("myweibo", "listadpter ---> getcount:" + adplist. size (); Return adplist. size () ;}@ overridepublic object getitem (INT position) {log. I ("myweibo", "listadpter ---> getitem"); Return adplist. get (position) ;}@ overridepublic long getitemid (INT position) {log. I ("myweibo", "listadpter ---> getitemid:" + position); Return Position + 10 ;}@ overridepublic view getview (INT position, View Convertview, viewgroup parent) {status tmpstu = adplist. get (position); convertview = Inflater. inflate (R. layout. homelistitem, null); textview TV1 = (textview) convertview. findviewbyid (R. id. ltmusername); tv1.settext (tmpstu. getuser (). getname (); textview TV2 = (textview) convertview. findviewbyid (R. id. lsmcontent); tv2.settext (tmpstu. gettext (); imageview iv1 = (imageview) convertview. findviewbyid (R. id. home_hea Dicon); If (! (Tmpstu. getuser (). getprofileimageurl ()). equals ("") {iv1.setimagebitmap (weiboutil. getbitmapfromurl (tmpstu. getuser (). getprofileimageurl ();} imageview iv2 = (imageview) convertview. findviewbyid (R. id. lsmweibopic); If (tmpstu. getthumbnail_pic ()! = "") {Iv2.setimagebitmap (weiboutil. getbitmapfromurlstring (tmpstu. getthumbnail_pic (); iv2.setvisibility (view. visible);} linearlayout sublay = (linearlayout) convertview. findviewbyid (R. id. sublayout); Status retsta = tmpstu. getretweeted_status (); If (retsta = NULL) {sublay. setvisibility (view. gone);} else {textview TV3 = (textview) convertview. findviewbyid (R. id. lsmretweedweibo); tv3.settext ("@" + retsta. getuser (). g Etname () + ":" + retsta. gettext (); If (retsta. getthumbnail_pic ()! = "") {Imageview iv3 = (imageview) convertview. findviewbyid (R. id. subweibopic); iv3.setimagebitmap (weiboutil. getbitmapfromurlstring (retsta. getthumbnail_pic () ;}} return convertview ;}}

 

Related Article

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.