ProgressDialog没有出现

时间:2011-09-02 21:11:04

标签: java android progressdialog

我的代码在ProgressDialog内开始AsyncTask,看起来像这样:

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

  

无法在未调用Looper.prepare()

的线程内创建处理程序

它指向调用ProgressDialog.show()的行。

3 个答案:

答案 0 :(得分:1)

您的对话框创建假设位于UI线程上,以便我可以将进度回发到对话框,使用对话框创建代码实现onPreExecute()。发布进度调用并实施onProgressUpdate (Progress... values)

答案 1 :(得分:1)

移动它:

dialog = ProgressDialog.show(Apps.this,
        "Retreiving Application list",
        "Retrieving list of installed applications", true);

到onPreExecute方法。

onPreExecute(和onPostExecute,你将取消对话框)在UI线程上发生,因此可以进行UI更改。 doOnBackground在不同的线程中工作,因此无法进行UI更改。

答案 2 :(得分:1)

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);

    }

}

尝试上面的类,我在onPreExecute方法中移动对话框创建,该方法在UI线程上运行

记住在UI线程上运行onPreExecute,onPostExecute和onProgressUpdate方法 doInBackground方法在非UI线程上运行