简体   繁体   English

Android在显示进度对话框的同时执行代码

[英]Android execute code while showing progress dialog

protected void showSpinner() {
    dialogSpin = ProgressDialog.show(activity, "", 
            "Loading. Please wait...", true);

    Thread t = new Thread(new Runnable(){

        @Override
        public void run() {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {


                    EverydayNotesAndroid3Activity.importAllCalendar();
                }
            });
        }

    });
    t.start();
}

I want to show the spinner while the thread is running. 我想在线程运行时显示微调器。 This way, I can show how my import of calendar is going to the user while I'm importing it. 这样,我可以显示在导入日历时如何将日历导入用户。

Problem : my Spinner dialog will only show when the import is done. 问题 :我的“微调器”对话框仅在导入完成后显示。 I don't know what I'm doing wrong, because according to my code it should show the dialog and then run the import (which takes 30 seconds), but once more, the dialog wait the end of the import to show up. 我不知道自己在做什么错,因为根据我的代码,它应该显示对话框,然后运行导入(这需要30秒),但是对话框又一次等待导入结束才显示出来。

Thanks for paying attention, ask for more info. 感谢您的关注,要求更多信息。

考虑研究Asynctasks

You are importing calender in UI thread it self. 您正在自行在UI线程中导入日历。 Then your progress dialog wait's until import has been done. 然后,您的进度对话框将一直等到导入完成。 Then again it will show. 然后它将再次显示。

If you want to display progress dialog, then import calender in another thread not in UI thread. 如果要显示进度对话框,则将日历输入到不在UI线程中的另一个线程中。

I would use an AsyncTask to import the calendar. 我将使用AsyncTask导入日历。 AsyncTask has three methods that can be overridden. AsyncTask具有三种可以被覆盖的方法。 You overwrite doInBackground and do all the stuff that is done in the background thread there. 您将覆盖doInBackground并执行在后台线程中完成的所有工作。 You can call publishProgress from your background task every time something should change in the UI. 每当UI中发生任何更改时,您都可以从后台任务调用publishProgress。 The AsyncTask will then call onProgressUpdate in the UI-Thread to allow you to show the progress to the user. 然后,AsyncTask将在UI线程中调用onProgressUpdate ,以允许您向用户显示进度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM