java - 进度对话框未出现

标签 java android progressdialog

我有在 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/

相关文章:

java - 如何比较单个字符串中的元素?

java - oauth2 spring-security 成功和失败处理程序

java - Box2DDebugRenderer 和 SpriteBatch 错位

java - 在 Spinner 中选择相同名称时,ScrollView 应滚动到特定 TextView

android - 如果 RecyclerView 为空则显示 Toast 消息

java - 如何在 AlertDialog 之后显示 ProgressDialog

java - 在 Java 线程池中使用守护线程不起作用

androidx.constraintlayout.widget.ConstraintLayout 无法转换为 android.widget.TextView

c# - Xamarin.android-如何更快地加密/解密图像

java - 监控 BufferedInputStream 下载进度