栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

由于AsyncTask是一个单独的类,如何将OnPostExecute()的结果获取到主要活动中?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

由于AsyncTask是一个单独的类,如何将OnPostExecute()的结果获取到主要活动中?

简单:

创建interface类,其中

class String output
是可选的,或者可以是您想要返回的任何变量。

public interface AsyncResponse {    void processFinish(String output);}

转到您的AsyncTask课程,并将interface声明AsyncResponse为字段:

public class MyAsyncTask extends AsyncTask<Void, Void, String> {  public AsyncResponse delegate = null;    @Override    protected void onPostExecute(String result) {      delegate.processFinish(result);    } }

在您的主要活动中,需要进行implements交互AsyncResponse。

public class MainActivity implements AsyncResponse{  MyAsyncTask asyncTask =new MyAsyncTask();  @Override  public void onCreate(Bundle savedInstanceState) {     //this to set delegate/listener back to this class     asyncTask.delegate = this;     //execute the async task      asyncTask.execute();  }  //this override the implemented method from asyncTask  @Override  void processFinish(String output){     //Here you will receive the result fired from async class      //of onPostExecute(result) method.   } }

更新

我不知道这是你们中许多人的最爱。因此,这是使用简单便捷的方式

interface

仍然使用相同的

interface
。仅供参考,您可以将其合并为
AsyncTask
类。

AsyncTask
课堂上:

public class MyAsyncTask extends AsyncTask<Void, Void, String> {  // you may separate this or combined to caller class.  public interface AsyncResponse {        void processFinish(String output);  }  public AsyncResponse delegate = null;    public MyAsyncTask(AsyncResponse delegate){        this.delegate = delegate;    }    @Override    protected void onPostExecute(String result) {      delegate.processFinish(result);    }}

在你的

Activity
课上做

public class MainActivity extends Activity {   MyAsyncTask asyncTask = new MyAsyncTask(new AsyncResponse(){     @Override     void processFinish(String output){     //Here you will receive the result fired from async class      //of onPostExecute(result) method.     }  }).execute(); }

或者,再次在Activity上实现接口

public class MainActivity extends Activity     implements AsyncResponse{    @Override    public void onCreate(Bundle savedInstanceState) {        //execute the async task         new MyAsyncTask(this).execute();    }    //this override the implemented method from AsyncResponse    @Override    void processFinish(String output){        //Here you will receive the result fired from async class         //of onPostExecute(result) method.    }}

如您所见,上面有2个解决方案,第一个和第三个,它需要创建method processFinish,另一个,该方法在调用者参数内部。第三个更整洁,因为没有嵌套的匿名类。希望这可以帮助

提示:变化

String output
String response
以及
String result
不同的匹配类型,以获得不同的对象。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/366719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号