Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, can I put AsyncTask in a separate class and have a callback?

I'm just learning about AsyncTask and want to use it as a separate class, rather then a subclass.

For example,

class inetloader extends AsyncTask<String, Void, String> {


    @Override
    protected String doInBackground(String... urls) {

        String response = "";

            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(urls[0]);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        return response;
    }


    @Override
    protected void onPostExecute(String result) {
        Log.e("xx",result);
        // how do I pass this result back to the thread, that created me?
    }


}

and the main(ui) thread:

inetloader il = new inetloader();
il.execute("http://www.google.com");
//il.onResult()
//{
    ///do something...
//}

Thanks!

like image 552
Roger Travis Avatar asked May 26 '12 17:05

Roger Travis


2 Answers

Use a interface. Something like:

interface CallBackListener{
  public void callback();
}

Then do this in your UI thread:

inetloader il = new inetloader();
li.setListener(this);
il.execute("http://www.google.com");

In inetloader, add:

   CallBackListener mListener;

   public void setListener(CallBackListener listener){
     mListener = listener;
   }

then In postExecute(), do:

   mListener.callback();
like image 147
Xi 张熹 Avatar answered Oct 09 '22 07:10

Xi 张熹


you can pass the activity instance to constructor and call activity function from there...
Like use interface :

public interface ResultUpdatable {

   public void setResult(Object obj);
   }

Implement this in the Activity and pass in the constructor of Async task and update the result from onPostExecute using setResult function.

like image 45
Dheeresh Singh Avatar answered Oct 09 '22 08:10

Dheeresh Singh