AsyncTask 类启动了许多其他线程,因为我使用的是第三方库。我不确定库打开了多少线程,但我想等待它们全部完成,然后再用它们获取的数据填充我的列表视图。
目前我正在睡 10000 毫秒,但这不切实际,因为我不知道它的列表有多大。
这个问题的正确解决方案是什么?
task = new mTask();
task.execute(appsList);
new Thread(new Runnable() {
public void run() {
populateList();
}
}).start();
}
private class mTask extends AsyncTask<List<ApplicationInfo>, Void, Void> {
ProgressDialog progress;
@Override
protected void onPreExecute() {
progress = new ProgressDialog(MainActivity.this);
progress.setIndeterminate(true);
progress.show();
super.onPreExecute();
}
@SuppressWarnings("deprecation")
@Override
protected Void doInBackground(List<ApplicationInfo>... params) {
appDataManager = new AppDataManager(MainActivity.this,
mySQLiteAdapter, MainActivity.this);
appDataManager.work(params[0]);
return null;
}
@Override
protected void onPostExecute(Void result) {
mySQLiteAdapter.close();
progress.dismiss();
super.onPostExecute(result);
}
}
@SuppressWarnings("deprecation")
public void populateList() {
try {
Thread.sleep(10000)
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
Cursor cursor;
mySQLiteAdapter.openToRead();
cursor = mySQLiteAdapter.queueAll();
ArrayList<String> appsList = new ArrayList<String>();
if (cursor.moveToFirst()) {
do {
appsList.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.moveToFirst();
ArrayAdapter<String> adp = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
appsList);
listContent.setAdapter(adp);
cursor.close();
mySQLiteAdapter.close();
Log.i("finished", "finished");
}
});
}
应用数据管理器
public void work(List<ApplicationInfo> appsList) {
List<ApplicationInfo> appList = appsList;
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
mySQLiteAdapter.close();
for (int i = 0; i < 5; i++) {
String name = appList.get(i).name;
String pack = appList.get(i).packageName;
// TODO AsyncTask
getHtml(pack, name);
}
}
public void getHtml(final String pack, final String name) {
String url = MARKET_URL + pack;
//AndroidQuery library. fetch html
aq.ajax(url, String.class, 1000, new AjaxCallback<String>() {
@Override
public void callback(String url, String htm, AjaxStatus status) {
Log.i("status", status.getMessage());
parseHtml(htm, pack, name);
}
});
}