I have code that starts a ProgressDialog
inside an AsyncTask
, it looks like this:
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();
}
}
I'm getting a RuntimeException
saying
Can't create handler inside thread that has not called Looper.pr开发者_高级运维epare()
It points at the line where ProgressDialog.show()
was called.
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);
}
}
try the above class , i moved the dialog creation in the onPreExecute method which runs on UI thread
Remember onPreExecute , onPostExecute and onProgressUpdate methods run on UI thread doInBackground method runs on non-UI thread
Your dialog creation is suppose to be on the UI thread so that I can post back progress to the dialog, implement onPreExecute()
with your dialog creation code. To post progress call and implement onProgressUpdate (Progress... values)
.
Move this:
dialog = ProgressDialog.show(Apps.this,
"Retreiving Application list",
"Retrieving list of installed applications", true);
To the onPreExecute method.
onPreExecute (and onPostExecute, where you will cancel the dialog) happens on the UI thread and therefore can make UI changes. doOnBackground works in a different thread and therefore can't make UI changes.
精彩评论