Android easy to implement network interaction templates
Source: Internet
Author: User
<span id="Label3"></p>After reading this article, you can learn:<br>1.Android templating approach to background interaction<br><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"></p></p><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">Use of 2.JSON</p></p><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">3. Check the network connection</p></p><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">Use of 4.AsyncTask</p></p><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">We simply use login as an example to implement the entire process. Talk not much, first look at:</p></p><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><p style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><br></p></p><p style="font-family:Arial; font-size:14px; line-height:26px"><p style="font-family:Arial; font-size:14px; line-height:26px"><span style="color:#ff0000"></span></p></p><p style="font-family:Arial; font-size:14px; line-height:26px"><p style="font-family:Arial; font-size:14px; line-height:26px"><span style="color:#ff0000"><br></span></p></p><p style="font-family:Arial; font-size:14px; line-height:26px"><p style="font-family:Arial; font-size:14px; line-height:26px"></p></p><p style="font-family:Arial; font-size:14px; line-height:26px"><p style="font-family:Arial; font-size:14px; line-height:26px"></p></p><p style="font-family:Arial; font-size:14px; line-height:26px"><p style="font-family:Arial; font-size:14px; line-height:26px"><br></p></p>first, the general class of the writing<br>first, since you want to achieve interactive templating, The most important thing is to extract as much reusable code as Possible. Regardless of what is done with the background, it is essential to determine whether the network is connected properly, to get the data after sending the request, and to prompt for error messages when the network is Abnormal. So we write a generic callservice class:<pre name="code" class="java">/** * Created by Hyman on 2015/6/11. */public class Callservice {/** * Check NET connection before call * * @param context * @return */ private static Boolean checknet (context Context) {connectivitymanager connectivity = (connectivitymanager) con Text. Getsystemservice (context.connectivity_service); If (connectivity! = Null) {//get network connection managed objects Networkinfo info = Connectivity.getactivenetworkinfo (); If (info! = null && info.isconnected ()) {//determine If the current network is connected if (info.getstat E () = = NetworkInfo.State.CONNECTED) {return true; }}} return false; }/** * Call service by Net * * @param urlstring URL * @param content a string of Json,params * @ Return the Result,a string of JSON */public static string call (string urlstring, string content, context Context) {if (!checknet(context)) {return null; } try {url url = new URL (urlstring); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5000); Conn.setdooutput (true); Conn.setrequestmethod ("POST"); Conn.setrequestproperty ("user-agent", "Fiddler"); Conn.setrequestproperty ("content-type", "application/json"); Conn.setrequestproperty ("Charset", "utf-8"); OutputStream OS = Conn.getoutputstream (); Os.write (content.getbytes ()); Os.close (); int code = Conn.getresponsecode (); If (code = =) {bufferedreader in = new BufferedReader (new inputstreamreader (conn.getinputstream (), UTF -8 ")); String retdata; String ResponseData = ""; While ((retdata = In.readline ()) = Null) {responsedata + = retdata; } in.clOSE (); Return responsedata; }} catch (malformedurlexception e) {e.printstacktrace (); } catch (unsupportedencodingexception E) {e.printstacktrace (); } catch (protocolexception E) {e.printstacktrace (); } catch (ioexception E) {e.printstacktrace (); } return null; public static void Showneterr (context Context) {new alertdialog.builder (context). settitle ("network Error Error "). setmessage (" network connection failed, Confirm network connection "). Setpositivebutton (" OK ", new Dialoginterface.onclicklisten ER () {@Override public void OnClick (dialoginterface arg0, int Arg1) { }}). Show (); } }</pre><br>Among them, the network connection status is determined by the Connectivitymanager method provided by the Android system, and with this class we can also get more connection status information, including current traffic or WiFi and so On.<br>then, when calling the core method call (), three parameters are passed in, one is the URL path of the background service, one is the parameters that have been assembled, and the third one is the contextual Context. In this method, we first determine the network connection, not connected to directly return Null. otherwise, The HttpURLConnection method is used to send the request to the server, and the return value of the server is returned to the Caller.<br>Another Showneterr method is simply to jump out of a dialog box to Prompt.<br><br>second, using JSON and asynctask to interact<br>We all know that these time-consuming operations, such as network operation in wirelessly, cannot operate on the main thread (that is, the UI thread), so we take advantage of the asynchronous mechanism provided by Android Asynctask (or We can write our own new Thread + Handler) for network Operation. Friends who do not understand asynctask usage can read my other blog about Android Asynctask in Detail. Let's take a login as an example:<pre name="code" class="java">/** * Created by Hyman on 2015/6/11. */public class Login {private static final String urlstring = Getserverurl.geturl () + "index.php?r=period/login"; private static final String TAG = "Login"; Private ProgressBar ProgressBar; Private context context; Private String userName; Private String password; Public Login (Context Context,progressbar ProgressBar) {this.progressbar=progressbar; This.context = context; } public void Login (String username,string password) {log.i (TAG, "call login"); this.username=username; this.password=password; New Logintask (). Execute (); } class Logintask extends asynctask<void, Void, string> {@Override protected String doinbackground (Void ... Params) {jsonobject tosendsobject = new Jsonobject (); LOG.I (TAG, "start put json!"); Try {//add account info tosendsobject.put ("username", username); Tosendsobject.put ("password", password); } catch (jsonexception E) {e.printstacktrace (); }//change JSON to string content = String.valueof (tosendsobject); LOG.I (TAG, "send:" + content); String responsedata = Callservice.call (urlstring, content,context); If (responsedata==null | | responsedata.equals ("")) {return null; } log.i (TAG, "res:" + responsedata); Jsonobject Resultobject = null; String result=null; Try {resultobject = new Jsonobject (responsedata); result = Resultobject.getstring ("result"); LOG.I (TAG, "result:" + result); } catch (jsonexception E) {e.printstacktrace (); } return result; } @Override protected void OnPreExecute () {progressbar.setvisibility (view.visible); Show the PROgressbar Super.onpreexecute (); } @Override protected void OnPostExecute (String Result) {progressbar.setvisibility (view.gone); Hide the ProgressBar if (result==null) {callservice.showneterr (context); Return } toast.maketext (context, "result:" +result,toast.length_short). show (); Here's can do anything-want after login}}}</pre><br>We initialize the instance of this class in the loginactivity, pass in the context and ProgressBar (to improve the user experience), and then call the login method to pass in the user name and password two Parameters. Before the operation, the OnPreExecute method shows the progressbar, and after returning the result, the OnPostExecute method hides the Progressbar.<br>Then we look at the Doinbackgroud method (this method listens to the name is asynchronous operation Ah): we create a jsonobject object, and then use the method of Key-value pairs (like Map) to pass in parameters, and finally to a string after the transfer to the Server. The json-formatted string returned by the server is converted to Jsonobject after the result is Obtained. If NULL is returned, indicating a problem with the connection, call the Showneterr method of the generic class. I took a picture of the log, which was not clear after the JSON format of the friend can Glimpse:<br><br><br>If there is a need to pass a list to the server, you can also use the Jsonarray class. Like what:<pre name="code" class="java"><pre name="code" class="java"> Jsonarray Jsonarray = new Jsonarray (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd hh:mm:ss"); Try { for (periodpo Peroid:localperiods) { //this is a list of my custom data structures jsonobject periodobject = new Jsonobject () ; Periodobject.put ("date", sdf.format (peroid.getdate ())); Periodobject.put ("tag", Peroid.gettag ()); Periodobject.put ("length", peroid.getlength ()); Jsonarray.put (periodobject); Turn each object into a jsonobject, and then put each of the objects into the array } tosendsobject.put ("periods", jsonarray); Add Account Info tosendsobject.put ("username", "test"), } catch (jsonexception e) { E.printstacktrace (); }</pre></pre><br><br>============= written in the back ========================<br>After I finished writing, I thought that the pass-through parameter could also be put in the general class, but it was not a very good way to extract that part of the Code. I hope that friends can make more suggestions, not hesitate to enlighten, thank you!<br>Ps: the code in the text does not understand or have comments friends are welcome to leave a message!<p><p>Android easy to implement network interaction templates</p></p></span>
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