Android uses its encapsulated Http, Thread, and Handler to Implement Asynchronous tasks

Source: Internet
Author: User

Android uses its encapsulated Http, Thread, and Handler to Implement Asynchronous tasks
The directory structure is as follows:

Http encapsulation:

The http protocol has two main fields: request and response. The structure of Http encapsulation is shown below.

(1) HttpRequestInter. java: As a request domain object, you should be able to obtain the client request address and httpRequest object so that you can obtain the client request parameters and other information. In additionpublic HttpResponseInter request() throws Exception;This method returns a response object after the request is executed (represented by the interface)

/*** Request interface * @ author xuliugen */public interface HttpRequestInter {// get httpRequest public HttpUriRequest getHttpRequest (); // obtain the http request url public String getRequestURL (); // request server: return a response object public HttpResponseInter request () throws Exception ;}

(2) HttpResponseInter. java, as the response object corresponding to (1), should have methods: Get the returned status code, get the returned stream, get the returned string data, etc, the following method is to obtain the corresponding data.

/*** Response interface * @ author xuliugen */public interface HttpResponseInter {// return status code public int statusCode (); // return the number of streams to the client public InputStream getResponseStream () throws IllegalStateException, IOException; // return the byte array public byte [] getResponseStreamAsByte () throws IOException to the client; // return the JSON data public String getResponseStreamAsString () throws ParseException, IOException to the client ;}

(3) This is HttpRequestImpl. java interface implementation class, we can see that we have not only implemented the HttpRequestInter interface but also implemented the ResponseHandler. The second is used to return data after the request is executed, stored in a response Handler.

Public class HttpRequestImpl implements HttpRequestInter, ResponseHandler
  
   
{Protected HttpUriRequest httpUriRequest; // The url used to obtain the request: private AbstractHttpClient abstractHttpClient; // client object // construct a public HttpRequestImpl (AbstractHttpClient httpClient) {this. export acthttpclient = httpClient;} // get method public HttpUriRequest getHttpRequest () {return httpUriRequest;} // obtain the request url public String getRequestURL () {return httpUriRequest. getURI (). toString ();} // execute req Uest request, and return ?? Response object interface public HttpResponseInter request () throws Exception {return response acthttpclient.exe cute (httpUriRequest, this ); // The passed ResponseHandler object}/*** inherits the method implemented by the ResponseHandler interface * The processing interface for the response object after execution */public HttpResponseInter handleResponse (HttpResponse response) throws ClientProtocolException, IOException {// return the class that implements HttpResponseInter: return to a response interface HttpResponseInter httpResponseInter = new HttpResponseImpl (response); // response return httpResponseInter ;}}
  

(4) The following is the implementation class of the interface: HttpResponseImpl. java can see an HttpResponse response object in the constructor, which is the response object returned by the handler after the request is executed.

/*** Interface implementation class * @ author xuliugen */public class HttpResponseImpl implements HttpResponseInter {private HttpResponse response; // HttpResponse object private HttpEntity entity; // HttpEntity object public HttpResponseImpl (HttpResponse response) throws IOException {this. response = response; HttpEntity tempEntity = response. getEntity (); // get the entity if (null! = TempEntity) {entity = new BufferedHttpEntity (tempEntity) ;}// return the response object status code public int statusCode () {return response. getStatusLine (). getStatusCode ();} // stream public InputStream getResponseStream () throws IllegalStateException, IOException {InputStream inputStream = entity. getContent (); return inputStream;} // The result is converted to string public String getResponseStreamAsString () throws ParseException, IOException {return EntityUtils. toString (entity);} // convert the obtained result to the character array public byte [] getResponseStreamAsByte () throws IOException {return EntityUtils. toByteArray (entity );}}

(5) The ExecuteHttpPost. java class inherits HttpRequestImpl. java and mainly writes two constructor methods in it. The constructor is the actual post Request Method and parameter settings:

/*** Is the place where the post request is actually executed ?? ** Inherit HttpRequestImpl to implement client-to-server ?? ** @ Author xuliugen **/public class ExecuteHttpPost extends HttpRequestImpl {public ExecuteHttpPost (optional httpClient, String url) {this (httpClient, url, null);} public ExecuteHttpPost (required httpClient, string url, HttpEntity entity) {super (httpClient); // httpClient this in the parent class. httpUriRequest = new org. apache. http. client. methods. httpPost (url); // initialize httpUriRequest if (null ! = Entity) {// set the parameter (HttpEntityEnclosingRequestBase) httpUriRequest). setEntity (entity );}}}

(6) Another important class is the implementation of the Client: BaseHttpClient. java sets a series of methods to implement the request methods of different clients, and how to convert the parameters of the client request to the parameter type of the post request, convert the returned data to the corresponding format, and cascade the call of the method.

/*** Top-level class of HttpClient client */public class BaseHttpClient {private AbstractHttpClient httpClient; public static final int DEFAULT_RETIES_COUNT = 5; protected int retriesCount = DEFAULT_RETIES_COUNT; // set the maximum number of connections public final static int MAX_TOTAL_CONNECTIONS = 100; // set the maximum wait time for obtaining the connection public final static int WAIT_TIMEOUT = 30000; // set the maximum number of connections of each route to public final static int MAX_ROUTE_CONNECTIONS = 100; // set the connection timeout time to public final static int CONNECT_TIMEOUT = 10000; // set the read timeout value to public final static int READ_TIMEOUT = 10000;/*** constructor, call the initialization method */public BaseHttpClient () {initHttpClient ();} /*** initialize the client parameter */private void initHttpClient () {// http parameter HttpParams httpParams = new BasicHttpParams (); // set the maximum number of connections ConnManagerParams. setMaxTotalConnections (httpParams, MAX_TOTAL_CONNECTIONS); // you can specify the maximum wait time for a connection. setTimeout (httpParams, WAIT_TIMEOUT); // set the maximum number of connections of each route. ConnPerRouteBean connPerRoute = new ConnPerRouteBean (MAX_ROUTE_CONNECTIONS); ConnManagerParams. setMaxConnectionsPerRoute (httpParams, connPerRoute); // you can specify the connection timeout value for HttpConnectionParams. setConnectionTimeout (httpParams, CONNECT_TIMEOUT); // you can specify the read timeout value for HttpConnectionParams. setSoTimeout (httpParams, READ_TIMEOUT); HttpProtocolParams. setVersion (httpParams, HttpVersion. HTTP_1_1); HttpProtocolParams. setContentCharset (httpParams, HTTP. UTF_8); SchemeRegistry schemeRegistry = new SchemeRegistry (); schemeRegistry. register (new Scheme (http, PlainSocketFactory. getSocketFactory (), 80); // set the port 80 schemeRegistry. register (new Scheme (https, SSLSocketFactory. getSocketFactory (), 443); // set port 443 // It is the ClientConnectionManager clientConnectionManager = new Queue (httpParams, SchemeRegistry) for managing the queue; httpClient = new Queue (clientConnectionManager, httpParams ); // create the handler httpClient for http reconnection. setHttpRequestRetryHandler (new BaseHttpRequestRetryHandler (retriesCount);}/*** converts the parameter to List
  
   
*/Private List
   
    
ParseParams (HashMap
    
     
Params) {if (params = null | 0 = params. size () {return null;} List
     
      
ParamsList = new ArrayList
      
        (Params. size (); for (Entry
       
         Entry: params. entrySet () {paramsList. add (new BasicNameValuePair (entry. getKey (), entry. getValue () +);} return paramsList;}/*** request to the server: */public String post (String url) throws Exception {return post (url, null ); // call post executed when there are parameters and set the parameter to null}/*** return T-type results after post Request */public
        
          T post (String url, HashMap
         
           Params, Class
          
            Clz) throws Exception {String json = post (url, params); return JSONUtil. fromJson (json, clz); // returns the result of converting to a specific type}/*** when the request has parameters, other functions call this method indirectly */public String post (String url, HashMap
           
             Params) throws Exception {// convert an input parameter to a parameter entity: Convert params to an object of enrity: Form entity UrlEncodedFormEntity entity = new UrlEncodedFormEntity (parseParams (params )); return request (url, entity ). getResponseStreamAsString ();}/*** returns the post execution Result directly */public Result postAsResult (String url, HashMap
            
              Params) throws Exception {return post (url, params, Result. class);}/*** returns the post execution result in the form of a Stream */public InputStream postAsStream (String url, HashMap
             
               Params) throws Exception {// convert the input parameter to the parameter entity UrlEncodedFormEntity entity = new UrlEncodedFormEntity (parseParams (params); return request (url, entity ). getResponseStream ();} public HttpResponseInter request (String url, HttpEntity entity) throws Exception {HttpRequestImpl httpRequestImpl = new ExecuteHttpPost (httpClient, url, entity); return httpRequestImpl. request ();}}
             
            
           
          
         
        
       
      
     
    
   
  

(7) The last one is the number of times that BaseHttpRequestRetryHandler. java is used in httpClient to implement repeated requests over the network.

/*** Http retry connection: Mainly used to complete the retry * @ author xuliugen */public class BaseHttpRequestRetryHandler implements HttpRequestRetryHandler {private int max_retry_count; // maximum number of attempts to connect public BaseHttpRequestRetryHandler (int maxretryCount) {this. max_retry_count = maxretryCount;} private static HashSet
  
   
> Predictionwhitelist = new HashSet
   
    
> (); Private static HashSet
    
     
> Predictionblacklist = new HashSet
     
      
> (); Static {exceptionWhiteList. add (NoHttpResponseException. class); exceptionWhiteList. add (UnknownHostException. class); exceptionWhiteList. add (SocketException. class); exceptionBlackList. add (SSLException. class); exceptionBlackList. add (InterruptedIOException. class); exceptionBlackList. add (SocketTimeoutException. class);} public boolean retryRequest (IOException exception, int executionCount, HttpConte Xt context) {if (executionCount> max_retry_count) {return false;} if (exceptionBlackList. contains (exception. getClass () {return false;} if (exceptionWhiteList. contains (exception. getClass () {return true;} HttpRequest request = (HttpRequest) context. getAttribute (ExecutionContext. HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (! Idempotent) {// is it true? Return true;} Boolean B = (Boolean) context. getAttribute (ExecutionContext. HTTP_REQ_SENT); boolean sent = (B! = Null & B. booleanValue (); if (! Sent) {return true;} return false ;}}
     
    
   
  
Combined use of Service and AsyncTask

The general process is as follows:

(1) We send tasks to the Service for processing in a unified manner. In this way, we need a Task entity. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> Public class Task {private int taskId; // Task ID private Map TaskParams; // The public static final int USER_LOGIN = 1; // the ID of a custom task. // The constructor and the get and set methods are omitted}

(2) below is the Service for unified management of tasks. In the Service, we not only need to manage tasks in a unified manner, but also need to manage the operations on the update interface, because operations to update the interface cannot be performed in the UI, we need to manage the activity in a unified manner. In Service, the operations to execute asynchronous tasks have been implemented by Thread and Handler.

Public class MainService extends Service implements Runnable {// task Queue: private static Queue used to store the task Queue
  
   
Tasks = new upload list
   
    
(); // Add the UI to be updated to the private static ArrayList appActivities = new ArrayList (); private boolean isRun; // whether to run the thread Handler = new handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case Task. USER_LOGIN: {// User Logon: Update UI // locate activity by name: Because MAinActivity implements the MainActivityInter interface, you can convert it to MainActivityInter type MainActivityInter activity = (MainActivityInter) getActivityByN Ame (MainActivity); activity. refresh (msg. obj. toString (); break;} default: break; }};};/*** Add a Task to the Task queue */public static void newTask (Task t) {tasks. add (t) ;}@ Override public void onCreate () {isRun = true; Thread thread = new Thread (this); thread. start (); super. onCreate ();}/*** enables the service to traverse and execute all the time */public void run () {while (isRun) {// listens to the Task task Task = null; if (! Tasks. isEmpty () {// determine whether task = tasks is in the queue. poll (); // After the task is executed, remove the change task from the task queue if (null! = Task) {doTask (task); // to do: Execution task} try {Thread. sleep (1000);} catch (Exception e) {}}// process the Task private void doTask (task Task) {Message msg = handler. obtainMessage (); msg. what = task. getTaskId (); switch (task. getTaskId () {case Task. USER_LOGIN: {// User Logon HashMap
    
     
ParamsHashMap = (HashMap
     
      
) Task. getTaskParams (); // access the network to determine whether the user has a String url = http: // 172.23.252.89: 8080/igouServ/userlogin. action; BaseHttpClient httpClient = new BaseHttpClient (); try {String result = httpClient. post (url, paramsHashMap); msg. obj = result; // return handler for processing} catch (Exception e) {e. printStackTrace ();} break;} default: break;} handler. sendMessage (msg) ;}@ Override public IBinder onBind (Intent intent ){ Return null;}/*** add an Activity object to the Set */public static void addActivity (Activity activity) {if (! AppActivities. isEmpty () {for (Activity ac: appActivities) {if (ac. getClass (). getName (). equals (ac. getClass (). getName () {appActivities. remove (ac); break ;}} appActivities. add (activity);}/*** get Activity object */private Activity getActivityByName (String Name) {if (! AppActivities. isEmpty () {for (Activity activity: appActivities) {if (null! = Activity) {if (activity. getClass (). getName (). indexOf (name)> 0) {return activity ;}}} return null;}/*** exit system */public static void appExit (Context context) {// Finish all the activities for (Activity: appActivities) {if (! Activity. isFinishing () activity. finish () ;}// end Service Intent service = new Intent (com. xuliugen. frame. task. mainService); context. stopService (service );}}
     
    
   
  

(3) to allow the Service to manage the activity in a unified manner, we can write an Interface MainActivityInter. java has two methods, one of which is to refresh the interface, so that we can perform interface operations in the service.

Public interface MainActivityInter {/*** initialization operation */public void init ();/*** refresh UI */public void refresh (Object... params );}
Test procedure

(1) Create MainActivity. java is mainly used to simulate a login operation. here we need to enable the Service. However, poor UN should like to create a task and add the task to the task queue managed by the Service, then other operations will be handed over to MainService. java (Service.

Public class MainActivity extends Activity implements MainActivityInter {private Button btn_login; private TextView textView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn_login = (Button) this. findViewById (R. id. btn_login); textView = (TextView) this. findViewById (R. id. textView1); // start the service Intent serviceIntent = new Intent (this, MainService. class); startService (serviceIntent); btn_login.setOnClickListener (new OnClickListener () {public void onClick (View v) {// The construction parameter is passed to the Task for Map processing.
  
   
ParamsHashMap = new HashMap
   
    
(2); paramsHashMap. put (userName, xuliugen); paramsHashMap. put (password, 123456); Task task Task = new Task (Task. USER_LOGIN, paramsHashMap); MainService. newTask (task) ;}}); // puts the activity into the MainService in the activity queue set. addActivity (this );} /******************* the following two methods are: *************** in the MainActivityInter Interface ************ * *******/public void init () {} public void refresh (Object... params) {// update the UI textView Based on the returned parameters. setText (params [0]. toString ());}}
   
  


 

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.