Android,我可以把AsyncTask在一个单独的类,并有一个callback?

我只是学习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... //} 

谢谢!

Related of "Android,我可以把AsyncTask在一个单独的类,并有一个callback?"

使用一个界面。 就像是:

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

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

 public interface ResultUpdatable { public void setResult(Object obj); } 

在Activity中实现这一点,并传入Async任务的构造函数,并使用setResult函数更新onPostExecute的结果。

 inetloader il = new inetloader(); il.execute("http://www.google.com"); String result = il.get();//put it in try-catch ^^^^^^^^ 

here you get result which is in onPostExecute(String result)