I get the following android exception when I try to open a dialog.
09-20 09:27:46.119: W/System.err(558): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
09-20 09:27:46.139: W/System.err(558): at android.view.ViewRoot.setView(ViewRoot.java:440)
09-20 09:27:46.139: W/System.err(558): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:181)
09-20 09:27:46.139: W/System.err(558): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
09-20 09:27:46.139: W/System.err(558): at android.app.Dialog.show(Dialog.java:269)
09-20 09:27:46.139: W/System.err(558): at android.app.AlertDialog$Builder.show(AlertDialog.java:907)
I'm calling dialog from a Service Android, and I tried the following code:
handler.post(new Runnable() {
public void run() {
try{
new AlertDialog.Builder(getApplicationContext()).setTitle("Alert!").setMessage("SIMPLE MESSAGE!").setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
} catch(Exception ex){
ex.printStackTrace();
}
}
});
You can't open a dialog from a service. Dialog is a UI component and it needs to be associated with a UI element (Activity). What you can do is to start an activity from your service that "looks like" a dialog. You can give the UI of an Activity a "DialogTheme" so that it looks like a standard Andrdoid dialog. Just search StackOverflow for "activity dialog theme".
i guess the problem is in
getApplicationContext()
may be it returns null, pass the right context...Step 1: Create class MyReciever:
Step 2: Create class MyService
Step 3: In MainActivity class start Service: