作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
经过几个小时的尝试,我仍然无法弄清楚如何将 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);
}
}
最佳答案
是的,这是可以做到的。
您必须将您的getPackages
逻辑移动到AsyncTask
的doInBackground
。当你想更新进度条时,你必须从 doInBackground
调用 publishProgress
。
一旦 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 将包含
新的 DownloadFilesTask().execute();
关于android - 如何将异步任务应用到这里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8366211/
我是一名优秀的程序员,十分优秀!