About the Android interface callback mechanism

Source: Internet
Author: User

In my previous post I showed what to perform asynchronous Web API calls on native Android code, after showing how to do it In native IOS a few days before. My Android Post is glaringly missing support for callback functions However, so today I'll show how to add that Functiona Lity in the Java world.



First we ll need to add some code to the class from where Apicall is called. This would be is what represents our reference to the callback function so we can call from a apicall (thanks to this Stack Overflow post for how to does this).



public interface ontaskcompleted{    void ontaskcompleted (jsonobject result); public class Callback implements ontaskcompleted{    @Override public    void ontaskcompleted (jsonobject result) {        //do something with result here!    }}



Now let's modify Apicall itself to accept the callback as a parameter.



public class Apicall extends Asynctask {private ontaskcompleted listener;    Private String result;    Public Apicall (ontaskcompleted listener) {This.listener=listener;        } protected Long Doinbackground (URL ... urls) {int count = Urls.length;        Long totalsize = 0;        StringBuilder Resultbuilder = new StringBuilder ();                for (int i = 0; i < count; i++) {try {//Read all the text returned by the server                InputStreamReader reader = new InputStreamReader (Urls[i].openstream ());                BufferedReader in = new BufferedReader (reader);                String resultpiece;                while ((resultpiece = In.readline ()) = null) {resultbuilder.append (resultpiece);             } in.close ();             } catch (Malformedurlexception e) {e.printstacktrace ();             } catch (IOException e) {e.printstacktrace ();           }  If Cancel () is called, leave the loop early if (iscancelled ()) {break;         }}//Save the result This.result = Resultbuilder.tostring ();     return totalsize; } protected void Onprogressupdate (Integer ... progress) {//update progress here}//called after DOINBAC        Kground finishes protected void OnPostExecute (Long result) {LOG.V ("result, yay!", This.result);            Put result into a JSON object try {jsonobject jsonobject = new Jsonobject (This.result);        Call Callback listener.ontaskcompleted (Jsonobject);        } catch (Jsonexception e) {e.printstacktrace (); }    }}



Just a few small changes from the original Callback-less class. Up top We added a new private variable of typeontaskcompleted, which we just defined. This is the object "listens" for us-to-send it a signal from this class, and then it executes the necessary action. Kind of like a callback!

We also defined a constructor just below this, the which now accepts an ontaskcompleted object as a paramter. So now you can pass in your callback if you create a new apicall. Down to the bottom, after receiving the response and putting our results nicely to a JSON object, we call this Callbac K with listener.ontaskcompleted (jsonobject); just as expected.

Finally, here are the would call this new version of Apicall from the other class where Callback is defined:



URL url = null;try {    url = new URL ("Http://search.twitter.com/[email protected]"),} catch (Malformedurlexception e) { C1/>e.printstacktrace ();} New Apicall (New Callback ()). Execute (URL);



Need to implement a callback the this asynchronous Web API call. By defining and passing a different callback if you create an Apicall object, you can effectively has apicall call what Ever function want after receiving, the results of the call.

Not as bad as I am expecting, but still a bit different from IOS and completely different from JavaScript. While coding moves + and more onto the web where slow calls over the Internet is common, it's hard don't to see language s like JavaScript taking ... But then again that's coming from a HTML5 fanboy playing around in native code.

About the Android interface callback mechanism

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.