如何知道外部类中的AsyncTasc已经完成?
我创建了一个 DataAdapter 类,它启动线程以从 Web 服务获取数据。当在活动中调用时,
DataAdapter.InitData();
我如何知道两个线程何时完成?
谢谢 七月
public class DataAdapter {
private final static String URL = "http://www.mywebservice.com";
private final static String URL_AD = "http://www.mywebservice2.com";
public void InitData(){
new GetInitData().execute(URL);
new GetAd().execute(URL_AD);
}
private static class GetInitData extends AsyncTask<String, Integer, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
}
}
private static class GetAd extends AsyncTask<String, Integer, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
}
}
}
I created a class DataAdapter
which launches threads to get data from webservices. When called in an activity using
DataAdapter.InitData();
how can I know when both threads are finished?
Thanks
Jul
public class DataAdapter {
private final static String URL = "http://www.mywebservice.com";
private final static String URL_AD = "http://www.mywebservice2.com";
public void InitData(){
new GetInitData().execute(URL);
new GetAd().execute(URL_AD);
}
private static class GetInitData extends AsyncTask<String, Integer, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
}
}
private static class GetAd extends AsyncTask<String, Integer, JSONObject> {
protected JSONObject doInBackground(String... urls) {
JSONObject json = RestJsonClient.getJSONObject(urls[0]);
return json;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(JSONObject json) {
//process data
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用这个:
}
Use this:
}
向 DataAdapter 类添加一个同步方法,每个 AsyncTask 在其 onPostExecute() 中调用该方法。在此方法中,您设置一个布尔变量,指示第一个作业已完成,当第二个 AsyncTask 调用该方法时,它会检查第一个线程是否已完成。如果两者都已完成,您可以使用自定义代码进行其中之一。
Add a synchronized method to you DataAdapter class which each of the AsyncTask calles in its onPostExecute(). Within this method you set a boolean variable indicating that the first job finished, when the second AsyncTask calls the method it checks whether the first thread has already finished. If both have finished you can go one with your custom code.