Android uses asynchronous task Asynctask to send a POST request for JSON data

Source: Internet
Author: User

Asynctask, a lightweight asynchronous class provided by Android, can directly inherit Asynctask, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution (UI Progress updates can be implemented via interfaces). The final feedback executes the result to the UI main thread.

Advantages of Use:

L Simple, fast

L Process controllable

Disadvantages of using :

L becomes complex when multiple asynchronous operations are used and UI changes are required.

2) The principle of handler asynchronous implementation and the advantages and disadvantages of its application


Asynctask IntroductionAndroid's Asynctask is more lightweight than handler and is suitable for simple asynchronous processing. The first thing to make clear is that Android has handler and Asynctask, both to not block the main thread (the UI thread), and that the UI update can only be done in the main thread, so asynchronous processing is unavoidable.

Android to reduce this development difficulty, provides the asynctask. Asynctask is a packaged background task class, as its name implies, an asynchronous task.

Asynctask directly inherits from the object class, where the position is android.os.AsyncTask. To work with Asynctask we are going to provide three generic parameters and overload several methods (at least one for overloading).

Asynctask defines three types of generic type params,progress and result.

    • The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.
    • Progress the percentage of background task execution.
    • Result background performs the final return of the task, such as String.

Students who have used Asynctask know that an asynchronous load of data must be overridden by the following two methods:

    • Doinbackground (Params ...) is performed in the background, and more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
    • OnPostExecute (Result) is equivalent to the way handler handles the UI, where it is possible to use the resulting processing action UI in Doinbackground. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

You also have to rewrite these three methods, if necessary, but not necessarily:

    • Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
    • OnPreExecute () Here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
    • Oncancelled () The action to be made when the user calls Cancel

Using the Asynctask class, here are a few guidelines to follow:

    • The instance of the task must be created in the UI thread;
    • The Execute method must be called in the UI thread;
    • Do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods;
    • The task can only be executed once, otherwise the exception will occur when multiple calls are made;

Here is a small demo I wrote, only for your reference, the results of the operation



The first is the Aysnctask class:

Package Ly.asynctasktest;import Android.content.context;import Android.os.asynctask;import Android.widget.TextView ; Import android.widget.toast;/** * Created by KFBMAC3 on 16/7/8. */* Asynctask is an abstract class that needs to inherit this class and then invoke the Execute () method. Note that inheritance requires the creation of three generic params, progress and result types, such as asynctask<void,inetger,void>: params refers to the type of arguments passed in when the Execute () method is called and DOINB        The parameter type of Ackgound () progress refers to the type of the parameter passed when the progress is updated, that is, the parameter type of publishprogress () and onprogressupdate () result refers to the return value type of Doinbackground ()        Doinbackgound () This method is inherited Asynctask must be implemented, running in the background, time-consuming operation can be done here publishprogress () update progress, to Onprogressupdate () pass the progress parameters Onprogressupdate () is called at the end of the publishprogress () call, updating the Progress */public class Updatetexttask extends Asynctask<void,integer,    string> {Private context context;    Private String URL;    Private String Postvalue;    private TextView text;        Updatetexttask (Context context, string string, String postvalue, TextView text) {this.context = Context;        This.url = string; This.posTValue = Postvalue;    This.text = text; /** * runs in the UI thread and executes before calling Doinbackground () * The method runs in the UI thread, and the UI space can be set in the UI thread */@Override PROTECTE    d void OnPreExecute () {Toast.maketext (context, "Start execution", Toast.length_short). Show (); }/** * Background Run method, can run non-UI thread, can execute time-consuming method * Here the void parameter corresponds to the first parameter in Asynctask * Here the string return value corresponds to the third parameter of the Asynctask * The method    Does not run in the UI thread, primarily for asynchronous operations, where space in the UI cannot be set and modified * but can be called by the Publishprogress method to trigger Onprogressupdate to manipulate the UI */@Override        Protected String doinbackground (Void ... params) {int i=0;            while (i<10) {i++;            Publishprogress update progress, give Onprogressupdate () pass the progress parameter publishprogress (i);            try {thread.sleep (1000);        } catch (Interruptedexception e) {}} String result = Common.postgetjson (Url,postvalue);    The third argument is a string, so return a string type of data return result; }/** * Here the string parameter corresponds to the third parameter in Asynctask (alsois the return value of the receiving Doinbackground) * runs in the UI thread, executes after Doinbackground () executes, the passed parameter is Doinbackground () The result of the returned */@Override PROTECTE        d void OnPostExecute (String i) {toast.maketext (Context,i,toast.length_short). Show ();    Text.settext (i); /** * is executed after publishprogress () is called, publishprogress () is used for update progress * Here the Intege parameter corresponds to the second parameter in Asynctask * in Doinbackground method, each call to the Publishprogress method triggers onprogressupdate execution * Onprogressupdate is executed in the UI thread, all can operate on the UI space */@Override Pro    tected void Onprogressupdate (Integer ... values) {//The second parameter is int text.settext ("" +values[0]); }}

Next is the method of sending the HTTP request:

Package Ly.asynctasktest;import Android.util.log;import Java.io.bytearrayoutputstream;import Java.io.dataoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.URL;import Java.util.list;import java.util.map;/** * Created by KFBMAC3 on 16/5/20.  */public class Common {public static string Postgetjson (string url, string content) {try {URL Murl            = new URL (URL);            HttpURLConnection mhttpurlconnection = (httpurlconnection) murl.openconnection ();            Set Link timeout time mhttpurlconnection.setconnecttimeout (15000);            Set Read timeout time mhttpurlconnection.setreadtimeout (15000);            Set the request parameter Mhttpurlconnection.setrequestmethod ("POST");            Add Header Mhttpurlconnection.setrequestproperty ("Connection", "keep-alive");            Receive input stream Mhttpurlconnection.setdoinput (true);            You need to turn on mhttpurlconnection.setdooutput when passing parameters (true); Post mode cannot beThe cache must be manually set to False Mhttpurlconnection.setusecaches (false);            Mhttpurlconnection.connect ();            DataOutputStream dos = new DataOutputStream (Mhttpurlconnection.getoutputstream ());            String postcontent = content;            Dos.write (Postcontent.getbytes ());            Dos.flush ();            After executing dos.close (), the POST request ends Dos.close ();            Gets the code return value int respondcode = Mhttpurlconnection.getresponsecode ();            LOG.D ("Respondcode", "respondcode=" +respondcode);            Gets the return content type String type = Mhttpurlconnection.getcontenttype ();            LOG.D ("type", "type=" +type);            Gets the character encoding of the returned content String encoding = mhttpurlconnection.getcontentencoding ();            LOG.D ("Encoding", "encoding=" +encoding);            Gets the returned content length, in bytes of int length = Mhttpurlconnection.getcontentlength (); LOG.D ("Length", "length=" + length);////Get header information for key//String key = MhttpurlconNection.getheaderfield (idx);//LOG.D ("Key", "key=" +key);            Get complete header information for map map<string, list<string>> map = Mhttpurlconnection.getheaderfields (); if (Respondcode = = 200) {//Get response Input Stream object InputStream is = Mhttpurlconnection.getinputstream ()                ;                Create byte output stream object Bytearrayoutputstream message = new Bytearrayoutputstream ();                Defines the length of the read int len = 0;                Define buffer byte buffer[] = new byte[1024];                    Loops through the buffer size while (len = is.read (buffer))! =-1) {//writes to the OS object based on the length of the read                Message.write (buffer, 0, Len);                }//Release resources is.close ();                Message.close ();                Returns string msg = new String (Message.tobytearray ());                LOG.D ("Common", msg);            return msg;            }return "fail";        }catch (Exception e) {return "error"; }    }}

Mainactivity:

Package Ly.asynctasktest;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.textview;import Java.net.URLEncoder;public    Class Mainactivity extends Appcompatactivity {private Button btn;    private TextView text;    Private String URL = "Http://192.168.24.104:3000/users";        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        BTN = (Button) Findviewbyid (R.ID.BTN);        Text = (TextView) Findviewbyid (R.id.text);                Btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Update ();    }        });                    private void Update () {try{String value = Urlencoder.encode ("username", "UTF-8") + "=" +                    Urlencoder.encode ("Anwei", "UTF-8") + "&" +Urlencoder.encode ("Userfullname", "UTF-8") + "=" + urlencoder.encode ("Viagra", "UTF-8");            Updatetexttask updatetext = new Updatetexttask (this, URL, value, text);        Updatetext.execute ();        }catch (Exception e) {text.settext ("error"); }    }}

The issue that needs attention is still to add network permissions in the Androidmanifest.xml file:

    <uses-permission android:name= "Android.permission.INTERNET"/>

The URL in this article is a simple background that I wrote in node. js, after I received the post information, I found the data in MongoDB and returned it, and the data received in the background


Want to try a friend can build a simple backstage, here on my Androidstudio project (does not include node. JS background) Click to open the link

If there are shortcomings, you are welcome to point out!!! If you have any ideas, you are welcome to guide!!!

Android uses asynchronous task Asynctask to send a POST request for JSON data

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.