Android,我可以把AsyncTask放在一个单独的类中并有一个回调吗?

2022-09-02 23:51:54

我只是在学习 AsyncTask,并希望将其用作单独的类,而不是子类。

例如

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...
//}

谢谢!


答案 1

使用接口。像这样:

interface CallBackListener{
  public void callback();
}

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

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

在 inetloader 中,添加:

   CallBackListener mListener;

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

然后在 postExecute() 中,执行:

   mListener.callback();

答案 2

您可以将活动实例传递给构造函数并从那里调用活动函数...
喜欢使用界面:

public interface ResultUpdatable {

   public void setResult(Object obj);
   }

在活动中实现此项,并在异步任务的构造函数中传递,并使用函数更新结果。onPostExecutesetResult


推荐