经过几个小时的尝试后,我仍然无法弄清楚如何将asynctask合并到下面的代码中。
我尝试过线程也无法正常工作。我想要做的就是在后台运行扫描并显示进度条。
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private void populateView() {
List<PackageInfo> adPackages = getAdPackages();
PackageManager pm = getPackageManager();
List<Map<String, String>> data = new ArrayList<Map<String, String>>(adPackages.size());
for(PackageInfo pkg : adPackages) {
Map<String, String> attrs = new HashMap<String, String>();
attrs.put("App Name", pm.getApplicationLabel(pkg.applicationInfo).toString());
attrs.put("Package Name", pkg.packageName);
data.add(attrs);
}
String[] from = new String[] {
"App Name",
"Package Name"
};
int[] to = new int[] {
android.R.id.text1,
android.R.id.text2
};
SimpleAdapter adapter = new SimpleAdapter(
this, data, android.R.layout.two_line_list_item, from, to);
setListAdapter(adapter);
mPackages = adPackages;
}
private List<PackageInfo> getAdPackages() {
Set<PackageInfo> adPackages = new HashSet<PackageInfo>();
//[...]
List<ApplicationInfo> appInfos = pm.getInstalledApplications(0);
for(ApplicationInfo appInfo : appInfos) {
try {
//[Heavy Stuff]
return new ArrayList<PackageInfo>(adPackages);
}
}
答案 0 :(得分:2)
是的,这可以做到。
您必须将getPackages
逻辑移至doInBackground
AsyncTask
。
当您想要更新进度条时,必须从publishProgress
致电doInBackground
。
完成doInBackground
后,调用onPostExecute
。将适配器和适配器本身的所有数据逻辑放入其中。也可以在功能中设置适配器。
以下是您可以参考的一些参考文档:
以下是一些示例:
private class GetPackageTask extends AsyncTask<Void, Integer, List<PackageInfo>> {
protected List<PackageInfo> doInBackground(URL... urls) {
// Put your code of getPackages in here
// You can call publish like it is done below
//for (int i = 0; i < count; i++) {
// totalSize += Downloader.downloadFile(urls[i]);
// publishProgress((int) ((i / (float) count) * 100));
//}
// adPackages is what you returning from your getPackages function
return adPackages;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(List<PackageInfo> result) {
// Here you will have all the setAdapter related code
}
}
onCreate将包含
new DownloadFilesTask()。execute();