1

我有一些特定的逻辑,其中需要等待 5 秒才能关闭微调器并显示对话框消息。一切正常,但未显示对话框消息。如果我毫不拖延地做同样的事情,它就会起作用。我的代码是:

public static void showMessageNotSentDialog(Activity inActivity)
{
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(inActivity);                       
    alertDialogBuilder.setTitle(R.string.error);         

    alertDialogBuilder.setMessage(R.string.error_sending_message);
    alertDialogBuilder.setCancelable(false);

    alertDialogBuilder.setPositiveButton(R.string.ok,new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
        }

    });

    AlertDialog alertDialog = alertDialogBuilder.create();      
    alertDialog.show();
}

public static void showDelayedErrorMessage(final Activity inActivity)
{

    Runnable task = new Runnable() {
        public void run() {
            com.test.classes.Spinner.hideSpinner();
            showMessageNotSentDialog(inActivity);

      }
      worker.schedule(task, com.test.classes.Spinner.TEXT_SPINNER_HIDEOUT_SEC, TimeUnit.SECONDS);
}

尝试从 UI 线程显示对话框:

public static void showDelayedErrorMessage(final Activity inActivity)
{

    Runnable task = new Runnable() {
        public void run() {
            com.test.classes.Spinner.hideSpinner();

            Runnable messageTask = new Runnable() {
                public void run() {
                    showMessageNotSentDialog(inActivity);
                }
              };
              inActivity.runOnUiThread(messageTask);
        }
      };

      worker.schedule(task, com.test.classes.Spinner.TEXT_SPINNER_HIDEOUT_SEC, TimeUnit.SECONDS);         
}
4

2 回答 2

1

您应该使用Handler,它可以更新 gui 线程。基本上,您可以延迟在处理程序上发布执行,这是一个示例:

Handler guiHandler = new Handler();
Runnable showDialog = new Runnable(){
   public void run(){
     //put here the dialog creation
   }
}

postDelayed (showDialog ,5000); // Post for 5 seconds

注意 Handler 的创建必须在 GUI 线程内,否则将无法工作。请记住,GUI 只能由主线程操作。

于 2013-03-13T19:49:28.043 回答
1

使用倒数计时器,无需使用线程

    new CountDownTimer(5000,5000) {

        @Override
        public void onTick(long arg0) {

        }

        @Override
        public void onFinish() {

        }
    }.start();

onfinish 在 5 秒后执行

于 2013-03-13T20:09:58.167 回答