Android: pass function reference to AsyncTask

后端 未结 3 550
温柔的废话
温柔的废话 2020-12-08 05:07

I\'m new to android and very used to web developing. in javascript when you want to perform an asynchronous task you pass a function as an argument (a callback):

<         


        
3条回答
  •  臣服心动
    2020-12-08 06:02

    In Java, functions are less of a first class citizen than in JavaScript. The AsyncTask provides the callback as a method in the class, which you should override.

    See Make an HTTP request with android for a subclass of AsyncTask with an implementation of the doInBackground which makes a web request.

    If you want to do multiple HTTP requests with different callbacks, you can override RequestTask and implement onPostExecute with the different callback implementations. You can use an anonymous class to simulate the closure a JavaScript callback commonly uses:

    new RequestTask(){
        @Override
        public void onPostExecute(String result) {
            // Implementation has read only access to 
            // final variables in calling scope. 
        }
    }.execute("http://stackoverflow.com");
    

    As Xaver shows, you can also create a full-blown interface for the listener. This seems only useful to me if you wish to implement a couple default onPostExecute functions and pick one of these default implementations for a particular call.

提交回复
热议问题