Android service dialog call error

When I try to open a dialog, I get the following exception for Android.

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 call in the Android service dialog 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(); } } }); 
0
android service dialog
source share
3 answers

You cannot open a dialog from a service. A dialog is a user interface component and must be associated with a user interface element (Activity). What you can do is get started with your service, which is β€œlike” a dialog. You can give the Activity user interface "DialogTheme" to look like a standard Andrdoid dialog. Just find StackOverflow for the "action dialog theme".

+1
source share

I think the problem in getApplicationContext() maybe it returns null, passes the correct context ...

0
source share

Step 1: Create MyReciever Class:

 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)){ Intent serviceIntent = new Intent(context, MyService.class); context.startService(serviceIntent); } Intent serviceIntent = new Intent(context, MyService.class); context.startService(serviceIntent); } } 

Step 2: Create MyService Class

 import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; public class MyService extends Service { public MyService() { } @Override public void onCreate() { //your SERVICE code here... super.onCreate(); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } } 

Step 3: In the launch class of the MainActivity Service:

 startService(new Intent(this, MyService.class)); 
0
source share

All Articles