Android 如何在正在运行的线程中显示警报对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12400620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:33:26  来源:igfitidea点击:

How to show alert dialog in a running thread?

androidandroid-alertdialoggame-loop

提问by user1602798

I'm developing an Android Game.In this game, There are tracks on which trains run. This is running thread. I want to show an alert dialog when there is a collision between. when I'm applying alert dialog showing error can't create handler inside thread that has not called looper.prepare().

我正在开发一个 Android 游戏。在这个游戏中,有火车运行的轨道。这是运行线程。我想在两者之间发生碰撞时显示一个警报对话框。当我应用显示错误的警报对话框时,无法在未调用的线程内创建处理程序looper.prepare()

回答by Ankitkumar Makwana

This will help you:

这将帮助您:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Your dialog code.
    }
});

回答by Daud Arfin

You must need to create AlertDialoginside UI thread else it will never work. If you are in different thread use MessageHandleror can use runOnUiThread(using runnable) to create your dialog inside.

您必须需要AlertDialog在 UI 线程内创建,否则它将永远无法工作。如果你在不同的线程中使用MessageHandler或者可以使用runOnUiThread(使用 runnable)在你的对话框里面创建。

回答by prakash

You can use Handlers to do this work.

您可以使用处理程序来完成这项工作。

Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
    @Override
    public void run() {
        // Your UI updates here
    }
});

回答by jeet

You can create an handler in Activity Class, and can invoke sendMessage to that handler object. Write code to display alert in handleMessage method of Handler, for Example:

您可以在 Activity 类中创建一个处理程序,并且可以调用该处理程序对象的 sendMessage。编写代码在Handler的handleMessage方法中显示alert,例如:

Activity Class

活动课

Handler mHandler = new Handler()
{
    public void handleMessage(Message msg)
    {
       //Display Alert
    }
};

//Thread

Thread thread= new Thread()
{
    public void run()
    {
         //Logic
         MHandler.sendEmptyMessage(0);
    }
}

回答by Sankar

You have to show your dialog on UI thread like below

您必须在 UI 线程上显示您的对话框,如下所示

runOnUiThread(new Runnable() {
                @Override
                public void run() {
                // Your dialog code.
                }
            });

回答by Виталий Фадеев

You can try this, with check App is visible

你可以试试这个,检查应用程序是可见的

Activity currentActivity = MainClassApp.getCurrentActivity();
boolean isAppVisible = currentActivity != null;

if (isAppVisible) {
    currentActivity.runOnUiThread(() -> 
    // Your Dialog Code 
}