How to show alert dialog in a running thread?

2019-02-10 07:16发布

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

6条回答
Emotional °昔
2楼-- · 2019-02-10 07:26

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
    }
});
查看更多
聊天终结者
3楼-- · 2019-02-10 07:30

You can try this, with check App is visible

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

if (isAppVisible) {
    currentActivity.runOnUiThread(() -> 
    // Your Dialog Code 
}
查看更多
唯我独甜
4楼-- · 2019-02-10 07:33

This will help you:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Your dialog code.
    }
});
查看更多
【Aperson】
5楼-- · 2019-02-10 07:46

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.

查看更多
The star\"
6楼-- · 2019-02-10 07:46

You have to show your dialog on UI thread like below

runOnUiThread(new Runnable() {
                @Override
                public void run() {
                // Your dialog code.
                }
            });
查看更多
The star\"
7楼-- · 2019-02-10 07:52

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);
    }
}
查看更多
登录 后发表回答