I have issue with displaying AlertDialog from Service. I am able to display custom layout window using Toast or using WindowManager(TYPE_SYSTEM_ALERT or TYPE_SYSTEM_OVERLAY). But, I do not want to use custom layout, I prefer to use nice AlertDialog GUI directly.
Scenario:
- Running Service. No active Activity present.
- On some external event, Service sends Notification
- When user press Notification, Service is informed via PendingIntent and AlertDialog should be displayed (created with
AlertDialog.Builder(this))
Error:
ERROR/AndroidRuntime(1063): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Searching for the answer lead me to impression that I am trying something that is currently not possible (Android 2.2). Or maybe it is.
Solution that matches described scenario has been found.
New Activity has been created and started from Service. However, it is activity with translucent background. Such activity does not have line
super.setContentView()inonCreate(). More important, to ensure transparency@android:style/Theme.Translucent
is entered under Theme tag for this activity in AndroidManifest.xml GUI. So, new line added to the manifest xml is
android:theme="@android:style/Theme.Translucent"In
onCreate()actual display of AlertDialog occursPress on AlertDialog buttons causes Dialog and Activity closing and sending of the Intent (or use of some other means) to deliver result to the Service.
Be sure that you defined setOnDismissListener() for the Dialog (implementation should call finish() on activity). If you do not do that press on the Back key cancels dialog but leaves you in the current activity which is transparent and looks to user like something is really wrong.