【问题标题】:How to set a timeout before showing a dialog Android?如何在显示对话框 Android 之前设置超时?
【发布时间】:2014-03-19 22:25:57
【问题描述】:

我正在尝试显示我制作的对话框,但在显示之前需要设置超时,就像您在 javascript 中使用 setTimeout 函数一样。有没有办法在 Android 中使用 java 做到这一点?

我曾尝试使用 Timer 实例,但在执行代码时出现此异常:

03-19 22:18:19.638: E/AndroidRuntime(2396): FATAL EXCEPTION: Timer-0
03-19 22:18:19.638: E/AndroidRuntime(2396): java.lang.RuntimeException: Can't create       
handler inside thread that has not called Looper.prepare()

这是代码:

            // instantiating a new CustomDialog class
            MyCustomDialog dialog = new MyCustomDialog(thisContext, R.layout.institutional_info_custom_list);
            DetailListView = (ListView) dialog.findViewById(R.id.custom_dialog_list);
            final MasterDetailArrayAdapter adapter = new MasterDetailArrayAdapter(ComeHaInvestito.this, MasterAndDetailstatisticsInfoList);         
            DetailListView.setAdapter(adapter);
            final MyCustomDialog showDialog = dialog;
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    showDialog.show();
                }
            }, 600);

我错了什么?我读到对话框绑定到 Acrivity 类,所以也许将 showDialog.show() 调用放在 new TimerClass() 中会引发异常?

顺便问一下,执行我所描述的操作的最佳方式是什么?

【问题讨论】:

    标签: java android timeout


    【解决方案1】:

    我弄错了什么?我读到对话框绑定到 Acrivity 类,所以也许将 showDialog.show() 调用放在新的 TimerClass() 让它抛出异常?

    问题是TimerTask 在后台线程上运行 - 因此问题-> 不能从后台线程调用任何会改变 UI 状态(例如显示对话框)的东西。 而是使用 Handler 和 postDelayed() 方法:

    伪代码:

    int counter = 0;
    ...
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
    
       public void run() {
    
           // it will be > 0 when run() will be called twice
           if (counter > 0) {
               dlg.show();
    
               // it made a trick now remove callbacks from Handler and return
               handler.removeCallbacks(runnable);
               return;
           }
    
           counter++;
           handler.postDelayed(runnable, 600);
    
       }
    };
    runnable.run();
    

    这种方法比runOnUiThread() 构造的可能用法更干净,并且可以在稍作修改的情况下定期调用。

    【讨论】:

    • 是的,我猜是因为这个,现在我在代码中添加了 runOnUiThread(new Runnable() {});它有效。你建议我对 Handler 做同样的事情,我该怎么做?
    • @user3019105 查看更新的答案。我添加了简单的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2013-12-17
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多