How to show alert dialog in a running thread?

2019-02-10 06:49发布

问题:

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().

回答1:

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



回答2:

This will help you:

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


回答3:

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 Class

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

//Thread

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


回答4:

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
    }
});


回答5:

You have to show your dialog on UI thread like below

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


回答6:

You can try this, with check App is visible

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

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