Android Asyntask processing return data and asyntask using Get,post request

Source: Internet
Author: User


Android is a single-threaded model, the Android interface (UI) drawing can only be done in the main thread, if the main thread in the time-consuming operation, it will affect the drawing of the UI and the response of the event. So on Android, it is not a time-consuming operation in the main line, otherwise there will be a program unresponsive (ANR) problem.
WORKAROUND: Open a new thread for time-consuming operation

Opening a new thread can be either new to thread () or implement Runnable interface

What to use Asynctask?

If you are using the thread's Run () method, the run () does not return a value after the end. So we have to set up a communication mechanism.

Asynctask all of the thread traffic is encapsulated into a callback function, and the invocation logic is easy to write. In particular, after the end of asynchronous processing, there are callback functions for finishing. Cough, are programmers lazy?

Android gives us a lightweight class for handling asynchronous tasks: Asynctask Of course it's the simple one.

Last but not least: Disable network operations in the UI thread after Android 4.0 ~ Otherwise it will be reported:android.os.NetworkOnMainThreadException

What is Asynctask (forgive the baby to steal the picture hehe but really explain it very clearly)

Attention:

The instance of the task must be created in the UI thread

The Execute method is created in the UI thread

An exception occurs when a task can be executed more than once in a single call

General purpose Asynctask and the use of network requests for return data in the main thread

What does universal Asynctask mean? Send different requests to return different types of data do you want a type to write a asynctask wouldn't it be trouble to die

There is another situation where we get an object from an asynchronous task and then immediately use the object logic at the same time, but it will then report a null pointer exception after running. What's going on here?

Asycntask starts a new thread, but the main thread does not stop and continues to run, it is used immediately, and your newly-opened thread may be accessing the network this object is empty

You can't be sure when the asycntask can get the data, the net is quick to a little bit good, network slow will wait a long time.

Look at a brief example of a small

First of all, we use asynchronous tasks to handle different types of data. Set this HTTP settings generic class third parameter return value type to generic no matter what type of data you are all OK

I've also written an interface as an HTTP property in the OnPostExecute method call where the Onresponse method implements the interface in test

The function of this interface can be fully understood as a listener event checkbox changes the listener trigger condition is whether to select this interface to listen to whether there is data to complete the network access data when the call

The implementation of the interface in the main thread has been implemented in the main thread the returned data is not a ~~~~~.

 Public classHttp<t>extendsAsynctask<string,void,t> {    PrivateOnresponselistener<t>Listener;  Public voidSetlistener (onresponselistener<t>listener) {         This. Listener =Listener; } @OverrideprotectedT doinbackground (String ... params) {return NULL; } @Overrideprotected voidOnPostExecute (T t) {Super. OnPostExecute (t); if(listener!=NULL) {listener.onresponse (t); }    }        //interface is similar to a listener event     Public InterfaceOnresponselistener<t>{        voidonresponse (T t); }}//test class to get data Public classTest {//the user object to get    PrivateUser user1=NULL;  Public voidget () {//Create a network access instanceHttp<user> http=NewHttp<user>(); //overriding InterfacesHttp.setlistener (NewHttp.onresponselistener<user>() {@Override Public voidonresponse (user user) {user1=user;        }        }); Http.execute ("Xxx.balabala.com"); }}

When sending a request, it is easy to take a parameter, the way of the request is nothing more than get,post the difference between the two plain English said get unsafe parameters through the URL directly passed the post security parameters encryption all of a sudden

Asynctask The core code Doinbackground method for Get and post requests

GET

  protectedT doinbackground (String ... params) {//Network Connection ObjectHttpURLConnection connection=NULL; //input stream Get network dataInputStream is=NULL; //byte array output streamBytearrayoutputstream bos=NULL; Try {            //Get network Connection objectConnection= (HttpURLConnection)NewURL (params[0]). OpenConnection (); //set GET request must be uppercaseConnection.setrequestmethod ("GET"); //Get network request Code 200 400 500 I don't know Baidu .            intCode=Connection.getresponsecode (); if(code==200){                //Get Streamis=Connection.getinputstream (); //Temporary byte array                byte[] b=New byte[1024]; intLen=-1; Bos=NewBytearrayoutputstream ();  while((Len=is.read (b))!=-1){                    //Write DataBos.write (b,0, Len); } String JSON=bos.tostring ("Utf-8"); T T=Json.parseobject (Json,type); returnT; }Else{LOG.E ("Error", "Network access failed ===========" +code); }        } Catch(IOException e) {e.printstacktrace (); }finally {            Try {                if(bos!=NULL) {bos.close (); }                if(is!=NULL) {is.close (); }            } Catch(IOException e) {e.printstacktrace (); }            if(connection!=NULL) {connection.disconnect (); }        }        return NULL; }

POST

The difference between post and get is that post has more code for processing parameters

   protectedT doinbackground (String ... params) {//the split URL is divided into two parts, address and parameterString[] Strarr=params[0].split ("\ \?")); HttpURLConnection Connection=NULL; //output StreamOutputStream os=NULL; //input StreamInputStream is=NULL; Bytearrayoutputstream Bos=NULL; Try{Connection= (httpurlconnection)NewURL (strarr[0]). OpenConnection (); Connection.setrequestmethod ("POST"); //set allow input output default true no write or YesConnection.setdooutput (true); Connection.setdoinput (true); OS=Connection.getoutputstream (); //Write parameters toOs.write (Strarr[1].getbytes ("Utf-8"));            Os.close (); intCode=Connection.getresponsecode (); if(code==200) { is=Connection.getinputstream (); byte[] b=New byte[1024]; intLen=-1; Bos=NewBytearrayoutputstream ();  while((Len=is.read (b))!=-1) {Bos.write (b,0, Len); } String JSON=bos.tostring ("Utf-8"); T T=Json.parseobject (Json,type); returnT; }Else{LOG.E ("Error", "Network access failed ===========" +code); }        } Catch(IOException e) {e.printstacktrace (); }finally {            Try {                if(bos!=NULL) {bos.close (); }                if(is!=NULL) {is.close (); }            } Catch(IOException e) {e.printstacktrace (); }            if(connection!=NULL) {connection.disconnect (); }        }        return NULL; }

Android Asyntask processing return data and asyntask using Get,post request

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.