gpt4 book ai didi

android - 如何将异步任务应用到这里

转载 作者:行者123 更新时间:2023-11-29 00:42:51 26 4
gpt4 key购买 nike

经过几个小时的尝试,我仍然无法弄清楚如何将 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 逻辑移动到AsyncTaskdoInBackground。当你想更新进度条时,你必须从 doInBackground 调用 publishProgress

一旦 doInBackground 完成,就会调用 onPostExecute。将适配器和适配器本身的所有数据逻辑放在其中。也在函数中设置适配器。

以下是您可以引用的一些引用文档:

Async Task Worker Threads

这是一些示例:

 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com