Android multi-thread handler, logoff, and Message application in HTTP-based systems

Source: Internet
Author: User
1. Background

When using the TCP/IP protocol for data transmission, iocp is often used. We often think that if HTTP can use the multi-thread mode for data interaction, it will bring a better user experience to the system/application. The focus of this study is to access the Web to obtain data and hand it over to another thread for processing. For detailed principles of handler, logoff, and message, refer to other blog posts. Here we recommend 《Android
Logoff and handler
AnalysisI was inspired to design a simple application framework.

2. Application functions/tasks

(1) connect to the server to obtain control commands;

(2) execute commands on the server;

(3) return the execution result;

3. Design

Shows the system design overview. The system consists of three threads: the main thread, the connection server thread, and the data processing thread.

3.1 Basic Principles

The main thread is used to set the timer and enable the thread. connectthread is used to connect to the server. The data obtained by connectthread is sent to dataprocessthread, while dataprocessthread is only used for data processing. After data processing is complete, the connectthread is notified of the result through message, and the connectthread returns the result to the server.

That is to say, in the whole process, connectthread is used for data interaction with the server, and dataprocessthread is used for data processing.

The Data Interaction Between the connectthread thread and dataprocessthread is completed through interfaces such as handler and loler. Connectthread and dataprocessthread each have a private logoff and a public handler.
(Set as handler1 and handler2 respectively) bind.

Note that the thread does not have a default logoff and can only be created by itself. And can only be created within the thread. Example: Create a handler inheritance class for each thread, while handlemessage is the real Method for Data extraction.

 

// Define the receiving message class threadhandler extends handler {public threadhandler (Looper loler) {super (Looper) ;}@ override public void handlemessage (Message MSG) in the subthread class) {Switch (MSG. what) {Case update_data: // constant getdata (); break; default: Break ;}}// receives data and processes the private thread deleethread = new thread () {public void run () {logoff. prepare (); // The logoff object of the current thread handler1 = new threadhandler (logoff. mylogoff (); logoff. loop ();}};

 

 

 

 

When two threads transmit data, you can use either of the following methods:

① Set the global variable response of the Request Response. After the connectthread requests data, it uses handler2.sendemptymessage (int
What) the method informs dataprocessthread, And once dataprocessthread receives an empty message from connectthread (because it is sent by sendemptymessage), it obtains data through response and executes the command;

② Connectthread uses the obtainmessage (INT what, int arg1, int arg2, object OBJ) and sendmessage packages in Android. OS. Handler.
(Message MSG) encapsulate the received data and send it to dataprocessthread. dataprocessthread then executes the command.

These two methods are like two methods when we get a mail. One is that people tell me that I am going to get two people and send them directly to me;

 

Test code: (add some Display Interfaces myself)

Package home. handler; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. util. timer; import Java. util. timertask; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. impl. client. defaulthttpclient; imp ORT android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. logoff; import android. OS. message; import android. view. view; import android. widget. button; import android. widget. edittext; public class phphphandleractivity extends activity {protected static final int update_text = 0; protected static final int return_result = 1; private handler handler1, handler2, handler3; private Edittext etget; // Private httppost request; // Private httpclient client; private httpresponse response = NULL;/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); etget = (edittext) findviewbyid (R. id. etget); // button function: Enable the final button mthreadstartbutton = (button) findviewbyid (R. id. bu Tton1); mthreadstartbutton. setonclicklistener (New button. onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubreceivethread. start (); timer = new timer (); timer. schedule (New mtask (), 30,100 0*60*2); mthreadstartbutton. setenabled (false );}});} //************************************** **************************************** * ********* // Add a user-defined function from here //*********** **************************************** * *********************************** Class myhandler extends handler {public myhandler (low.logoff) {super (logoff) ;}@ override public void handlemessage (Message MSG) {super. handlemessage (MSG); etget. settext ("handler of the main thread, received the message:" + (string) MSG. OBJ) ;}} // return the execution result handler class returnhandler extends handler {public returnhandler (low.low.low.) {super (low );} @ Override public void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. what) {Case return_result: phpweb (); break; default: Break ;}}// timer thread, connection server thread private class mtask extends timertask {@ override public void run () {// connect to the server httpresponse response = phpweb (); If (response! = NULL) handler1.sendemptymessage (update_text); logoff. prepare (); // The logoff object of the current thread handler3 = new returnhandler (logoff. mylogoff (); logoff. loop () ;}}// define the class threadhandler extends handler {public threadhandler (Looper loler) {super (lohand );} @ override public void handlemessage (Message MSG) {Switch (MSG. what) {Case update_text: getdata (); break; default: Break ;}}// receives data and processes private th Read privileges ETHREAD = new thread () {public void run () {loid. prepare (); // The logoff object of the current thread handler1 = new threadhandler (logoff. mylogoff (); logoff. loop () ;}}; // the data stream is converted to the Private Static string convertstreamtostring (inputstream is) {bufferedreader reader = new bufferedreader (New inputstreamreader (is )); stringbuilder sb = new stringbuilder (); string line = NULL; try {While (line = reader. readline ())! = NULL) {sb. append (LINE + "\ r \ n") ;}} catch (ioexception e) {e. printstacktrace ();} finally {try {is. close ();} catch (ioexception e) {e. printstacktrace () ;}} return sb. tostring ();} // access the Web function private httpresponse phpweb () {try {httpclient client = new defaulthttpclient (); string url = "http://www.google.com "; httpget httpgetrequest = new httpget (URL); // response = client.exe cute (httpgetrequest); Return Resp Onse;} catch (exception e) {// todo: handle finished tione. printstacktrace ();} return response;} // The Private void getdata () {try {httpentity entity = response. getentity (); // The returned value is not null if (entity! = NULL) {inputstream instream = entity. getcontent (); string result = convertstreamtostring (instream); // return the received data to the main interface: main thread -- construct others' handlerhandler2 = new myhandler (loaning. getmainlomessage (); message msg2 = handler2.obtainmessage (, 1, result); handler2.sendmessage (msg2); handler3.sendemptymessage (return_result) ;}} catch (exception e ){}}}

 

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.