android 在执行任务期间一直显示一个dialog

来源:互联网 发布:年龄大可做网络主播吗 编辑:程序博客网 时间:2024/04/29 11:02

在android 4.0源码的短信代码里面新增加了一个功能,能在加载图片的过程中一直显示一个dialog。


packages/apps/Mms/src/com.android.mms/ui/ComposeMessageActivity.java

定义它:

private void runAsyncWithDialog(final Runnable task, final int dialogStringId) {        new ModalDialogAsyncTask(dialogStringId).execute(new Runnable[] {task});    }

创建一个异步任务:

private class ModalDialogAsyncTask extends AsyncTask<Runnable, Void, Void> {        final int mDialogStringId;        /**         * Creates the Task with the specified string id to be shown in the dialog         */        public ModalDialogAsyncTask(int dialogStringId) {            this.mDialogStringId = dialogStringId;            // lazy initialization of progress dialog for loading attachments            if (mProgressDialog == null) {                mProgressDialog = createProgressDialog();            }        }        /**         * Initializes the progress dialog with its intended settings.         */        private ProgressDialog createProgressDialog() {            ProgressDialog dialog = new ProgressDialog(ComposeMessageActivity.this);            dialog.setIndeterminate(true);            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);            dialog.setCanceledOnTouchOutside(false);            dialog.setCancelable(false);            dialog.setMessage(ComposeMessageActivity.this.                    getText(mDialogStringId));            return dialog;        }        /**         * Activates a progress spinner on the UI.  This assumes the UI has invoked this Task.         */        @Override        protected void onPreExecute() {            // activate spinner after half a second            mAttachmentEditorHandler.postDelayed(mShowProgressDialogRunnable, 500);        }        /**         * Perform the specified Runnable tasks on a background thread         */        @Override        protected Void doInBackground(Runnable... params) {            if (params != null) {                try {                    for (int i = 0; i < params.length; i++) {                        params[i].run();                    }                } finally {                    // Cancel pending display of the progress bar if the image has finished loading.                    mAttachmentEditorHandler.removeCallbacks(mShowProgressDialogRunnable);                }            }            return null;        }        /**         * Deactivates the progress spinner on the UI. This assumes the UI has invoked this Task.         */        @Override        protected void onPostExecute(Void result) {            if (mProgressDialog != null && mProgressDialog.isShowing()) {                mProgressDialog.dismiss();            }        }    }


使用它:(参数:处理的任务,以及显示在dialog上的字符串的id)

runAsyncWithDialog(new Runnable() {                    public void run() {                        addAttachment(mimeType, uri, false);                    }                }, R.string.adding_attachments_title);