【问题标题】:What is the best way for AsyncTask to notify parent Activity about completion?AsyncTask 通知父 Activity 完成的最佳方式是什么?
【发布时间】:2012-11-16 12:32:00
【问题描述】:
public class ListingFoundBeaconService 
                    extends AsyncTask<String, String, String> {

    public ListingFoundBeaconService(Context contextGiven, 
                                     JSONObject jsonParams) {
        this.contextGiven = contextGiven;
        this.jsonParams = jsonParams;
    }

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(contextGiven);
        pDialog.setMessage("Loading list of active Beacons..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        Log.d("onPreExecute","onPreExecute worked" );
    }

    protected String doInBackground(String... args) {}

    protected void onPostExecute(String file_url) {   
        // Two activities will need this thread so I have 
        // kept this as a separate class. Here I want to send a
        // boolean value to the parent activity to show that 
        // the task has completed or not.
    }

我可以在onPostExecute() 函数中触发通知或完成事件侦听器,以便通知启动此类(ListingFoundBeaconService)的父类吗?标准的做法是什么?

【问题讨论】:

    标签: android android-asynctask android-activity


    【解决方案1】:

    最好的方法是调用委托。在你的 AsyncTask 类中创建一个构造函数并有一个委托

    委托接口:

    public interface TaskDelegate {
        public void taskCompletionResult(String result);
    }
    

    现在在AsyncTask:

    private TaskDelegate delegate;
    
    public ListingFoundBeaconService(Context contextGiven, 
                                     JSONObject jsonParams,
                                     TaskDelegate delegate) {
        this.contextGiven = contextGiven;
        this.jsonParams = jsonParams;
        this.delegate = delegate;
    }
    

    postExecute:

    delegate.taskCompletionResult(result/msg/json);
    

    在您的主类中实现TaskDelegate 并实现一个在任务完成时调用的方法。

    【讨论】:

    • 我发现了这个256design.com/blog/asynctask-in-android-and-oncompletelistener任何关于使用这个的cmets ??
    • 我看到你的链接它是 android 特定的,我们专注于 java 本机代码,特别是链接代码,除了链接概念之外的匿名内部类的负担将起作用,但你可以设置两个函数失败和你的代表也取得了成功。享受
    • taskDelegateResult ??它应该是 taskCompletionResult
    • 在我的主类中,我正在传递像这样的引用 TaskDelegateReference = this; ListingFoundBeaconService Lfb_object = new ListingFoundBeaconService(findBeaconContext,jsonData,TaskDelegateReference);
    • 这不是最好的方法。如果重新创建 Activity 会发生什么?当前(重新创建的)活动永远不会收到回调。
    【解决方案2】:

    将 ListingFoundBeaconService 类抽象化,然后在调用类中重写 onPostExecute。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 2011-09-29
      • 2020-02-26
      • 1970-01-01
      相关资源
      最近更新 更多