如果 AsyncTask 类嵌套在 Activity 类中,我只能访问 Activity GUI(findViewById()
等)。这使我的代码文件变得更大且可读性更差。
这个问题是否有解决方法,或者所有使用 GUI 方法的 AsyncTasks
通常都嵌套在 Activity 类中?
最佳答案
你可以写一个回调接口(interface)。然后您可以在您的 Activity 中实现。当您的异步任务被执行时,您可以将您的响应发送回 Activity 并相应地更新 UI。
interface IWebServiceResponse{
void onResponse(String response);
}
class MyActivity extends Activity implements IWebServiceResponse{
// override the method
onCreate(){
MyAsyncTask mt = new MyAsyncTask(MyActivity.this);
}
}
class MyAsyncTask extends AsyncTask{
// your code
IWebServiceResponse obj;
MyAsyncTask(IWebServiceResponse obj){
this.obj = obj;
}
onPostExecute(String response){
obj.onResponse(response);
}
}
关于android - 在单独的文件中使用 GUI 的 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44567153/