How to show alert dialog in a running thread?
Asked Answered
M

6

9

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

Memoir answered 13/9, 2012 at 6:29 Comment(0)
B
11

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.

Buhr answered 13/9, 2012 at 6:32 Comment(0)
I
15
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Your dialog code.
    }
});
Icky answered 13/9, 2012 at 6:33 Comment(0)
B
11

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.

Buhr answered 13/9, 2012 at 6:32 Comment(0)
R
7

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
    }
});
Reception answered 13/9, 2012 at 6:36 Comment(1)
you need initializate variable Handler mHandler= new Handler();Ama
V
6

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);
    }
}
Volleyball answered 13/9, 2012 at 6:41 Comment(0)
H
3

You have to show your dialog on UI thread like below

runOnUiThread(new Runnable() {
                @Override
                public void run() {
                // Your dialog code.
                }
            });
Hiedihiemal answered 13/9, 2012 at 6:31 Comment(0)
T
0

You can try this, with check App is visible

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

if (isAppVisible) {
    currentActivity.runOnUiThread(() -> 
    // Your Dialog Code 
}
Tooth answered 22/11, 2018 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.