我有在 AsyncTask
中启动 ProgressDialog
的代码,它看起来像这样:
class RetrieveApps extends AsyncTask<String, Void, List<ApplicationInfo>> {
PackageManager pm;
@Override
protected List<ApplicationInfo> doInBackground(String...params) {
dialog = ProgressDialog.show(Apps.this,
"Retreiving Application list",
"Retrieving list of installed applications", true);
pm = getPackageManager();
return pm.getInstalledApplications(PackageManager.GET_META_DATA);
}
@Override
protected void onPostExecute(List<ApplicationInfo> result) {
for(ApplicationInfo nfo : result){
Drawable icon = nfo.loadIcon(pm);
String name = nfo.loadLabel(pm).toString();
if(name != null && icon != null){
apps.add(new App(name, icon));
}
}
dialog.dismiss();
}
}
我收到一个RuntimeException
说
Can't create handler inside thread that has not called Looper.prepare()
它指向调用 ProgressDialog.show()
的行。
最佳答案
public class RetrieveApps extends AsyncTask<String, Void, List<ApplicationInfo>> {
PackageManager pm;
@Override
protected List<ApplicationInfo> doInBackground(String...params) {
pm = getPackageManager();
return pm.getInstalledApplications(PackageManager.GET_META_DATA);
}
@Override
protected void onPostExecute(List<ApplicationInfo> result) {
for(ApplicationInfo nfo : result){
Drawable icon = nfo.loadIcon(pm);
String name = nfo.loadLabel(pm).toString();
if(name != null && icon != null){
apps.add(new App(name, icon));
}
}
dialog.dismiss();
}
@Override
protected void onPreExecute(){
dialog = ProgressDialog.show(Apps.this,
"Retreiving Application list",
"Retrieving list of installed applications", true);
}
}
尝试上面的类,我将对话框创建移到了在 UI 线程上运行的 onPreExecute 方法中
记住 onPreExecute 、 onPostExecute 和 onProgressUpdate 方法在 UI 线程上运行 doInBackground方法在非UI线程上运行
关于java - 进度对话框未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7289257/