AsyncTask 通知父 Activity 完成的最佳方式是什么? [英] What is the best way for AsyncTask to notify parent Activity about completion?
本文介绍了AsyncTask 通知父 Activity 完成的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
) 的父类?这样做的标准方法是什么?
Can I trigger a notification or complete event listener in onPostExecute()
function so that the parent class which started this class(ListingFoundBeaconService
) is notified? What is the standard way of doing it?
推荐答案
最好的方法是调用delegate.在你的 AsyncTask
类中创建一个构造函数并有一个委托
Best way is to call delegate. In your AsyncTask
class make a constructor and have a delegate
委托接口:
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
并实现一个在任务完成时调用的方法.
In your main class implement TaskDelegate
and implemented a method which is called when the task completed.
这篇关于AsyncTask 通知父 Activity 完成的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文