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()
.
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.
runOnUiThread(new Runnable() {
@Override
public void run() {
// Your dialog code.
}
});
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.
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
}
});
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);
}
}
You have to show your dialog on UI thread like below
runOnUiThread(new Runnable() {
@Override
public void run() {
// Your dialog code.
}
});
You can try this, with check App is visible
Activity currentActivity = MainClassApp.getCurrentActivity();
boolean isAppVisible = currentActivity != null;
if (isAppVisible) {
currentActivity.runOnUiThread(() ->
// Your Dialog Code
}
© 2022 - 2024 — McMap. All rights reserved.