N秒后从RunOnUiThread中解除自定义对话框

时间:2013-01-16 15:30:41

标签: android multithreading dialog xamarin.android android-alertdialog

我有一个自定义对话框,它由以下代码创建:

public DialogFragment CreateNewPostedMessageDialog(CardSwipeData data, 
    List<MessagesMap> messagesMap, 
    string fbProfileimageAsByteString, 
    Context context) {
            DialogFragment newFragment = 
                new NewPostedMessageDialogFragment(data, messagesMap,
                                                   fbProfileimageAsByteString, 
                                                   context);
            return newFragment;
        }

从我的Activity的OnResume RunOnUiThread调用它:

ThreadPool.QueueUserWorkItem(state => {
    // Processing stuff here               

    RunOnUiThread(() => {
        DialogFragment dialog = CreateNewPostedMessageDialog(cardSwipeData,
           messagesMap, bitmapByteString, this);

        dialog.Show(FragmentManager, "PostedMessage");

        // ListAdapter gets updated here

        Thread.Sleep(3000);

        dialog.Dismiss();
    });
});

我想在3秒后解雇我的对话框,但发生的事情是我的对话框从未显示但我的列表仍然在3秒后更新。我睡觉时有什么问题吗?

2 个答案:

答案 0 :(得分:2)

由于runOnUiThread在UI线程上运行

Thread.Sleep(3000);

阻止UI线程三秒钟,使UI无响应。如果您想在三秒钟后关闭对话框,可以使用Handler类中的p ostDelayed()

Declare an Handler handler = new Handler();

然后,在runOnUiThread内更改您发布的代码:

   {

      final DialogFragment dialog = CreateNewPostedMessageDialog(cardSwipeData,
       messagesMap, bitmapByteString, this);

     dialog.Show(FragmentManager, "PostedMessage");

    // ListAdapter gets updated here

     handler.postDelayed( new Runnable() {

          @Override
          public void run() {
             dialog.Dismiss();
          }
     }, 3000) ;

});

检查拼写错误

答案 1 :(得分:1)

你做错了,你正在睡觉UI线程,而不是你在TreadPool中产生的后台线程。请尝试使用此功能:

ThreadPool.QueueUserWorkItem(state => {
    // Processing stuff here               

    DialogFragment dialog;

    RunOnUiThread(() => {
        dialog = CreateNewPostedMessageDialog(cardSwipeData,
           messagesMap, bitmapByteString, this);

        dialog.Show(FragmentManager, "PostedMessage");
    });

    // ListAdapter gets updated here
    Thread.Sleep(3000);

    RunOnUiThread(() => dialog.Dismiss()); 
});