Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...