How Can I Display an alert when push notification arrives from C2DM or GCM. Right now I am displaying notifications on status bar. So How can I get a notification as an alert.

- 459
- 6
- 19

- 6,177
- 6
- 30
- 40
-
What do you consider an "alert" to be? Bear in mind that users like `Notifications` to let them know about things in the background, unless the event is really really important. – CommonsWare Oct 09 '12 at 15:35
2 Answers
Popping a dialog in the middle of something a user is doing is a wildly user hostile thing to do. What if they're playing Angry Birds and you've just ruined their shot? Only the platform can and should get away with that.
Use the notification area, like Google intended, UNLESS you app currently has control (your activity is in running state). Then just use that activity's context to pop an AlertDialog()
. You can detect if the activity is running by overriding onResume()
and onPause()
- anything that happens in between is your activity's time.
An AlertDialog can be popped like this:
new AlertDialog.Builder(Ctxt) //Use an activity object here
.setMessage(R.string.MyMessageID) //Provide a message here... A string or a string ID will do
.setCancelable(true) //If you want them to be able to dismiss with a Back button
.setNegativeButton(R.string.IDS_NO, null) //No action on NO, right?
.setPositiveButton(R.string.IDS_YES, OnYesClickListener) //Plug your own listener...
.create()
.show();
For a simple message/Yes/No dialog, an AlertDialog
would suffice. For more complicated UI, derive a class from Dialog
and design your own layout.

- 59,826
- 25
- 160
- 281
-
-
1
-
However, using intent service as context doesn't work here. Error: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application – M.Y. Jun 18 '14 at 14:43
-
If there's an active activity, use that activity. If there isn't, see my answer. – Seva Alekseyev Jun 18 '14 at 21:24
-
And one more thing run the code in UI thread by calling the function activity.runOnUiThread() – Sakkeer Hussain Mar 19 '15 at 11:59
For Alert you need to write code in
generateNotification(Context context, String message)
in this method.
Thanks

- 6,213
- 2
- 27
- 37
-
can u explain more coz i am a new on push notification. Please expand your answer . – URAndroid Oct 09 '12 at 15:41
-
if you any push notification then GCMBaseIntentService on onMessage method notify that one message receive via push notification then call the generateNotification method to generate Notification and show it android status bar...I think it help you. – Md Abdul Gafur Oct 09 '12 at 15:47
-
I want to notify the user that a push is arrived when some app is in foreground. I want to do this using alert Dialog box with YES or NO options. – URAndroid Oct 09 '12 at 15:53