本文介绍了Android,我可以将 AsyncTask 放在单独的类中并进行回调吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习 AsyncTask 并希望将它用作一个单独的类,而不是一个子类.

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

例如

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?
    }


}

和主(ui)线程:

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

谢谢!

推荐答案

使用接口.类似的东西:

Use a interface. Something like:

interface CallBackListener{
  public void callback();
}

然后在您的 UI 线程中执行此操作:

Then do this in your UI thread:

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

在inetloader中,添加:

In inetloader, add:

   CallBackListener mListener;

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

然后在 postExecute() 中,执行:

then In postExecute(), do:

   mListener.callback();

这篇关于Android,我可以将 AsyncTask 放在单独的类中并进行回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:22