3

I have an Android library that has a Service that creates a Notification. From what I understand Notification must have a contentIntent (PendingIntent) set or a runtime exception will be thrown.

The problem is that I want users to be able to use this Service as is, or extend it, so that they can set the PendingIntent themselves through a callback during the creation of the Notification. However, if they choose not to do this, I need to set the PendingIntent to something so that there is no exception. Is there any way to create a dummy PendingIntent that just acts as a fill-in?

Here's an example of the code from the createNotification method:

PendingIntent p;
if(getPendingIntentCallback != null) {
    p = getPendingIntentCallback.getPendingIntent();
}
else {
    p = ?;
}
notification.contentIntent = p;
Eliezer
  • 7,209
  • 12
  • 56
  • 103

2 Answers2

8
PendingIntent pi=PendingIntent.getBroadcast(this, 0, new Intent("DoNothing"), 0);

This worked for me. It will launch a broacast for a "DoNothing" action. I hope nobody will listen for a "DoNothing" broadcast and do something as a reaction to it. But if you prefer you can construct something more exotic. Note: I'm using this just as a temporary placeholder. I will substitute it with something more useful for the user as I will advance in my application development.

mikk
  • 81
  • 1
  • This is a nice answer for someone generalizing the original question. In my case I'm defining a set of Notification actions, most of which do *something* through a broadcast or getActivity, but the user needs to be reminded the have the option to "do nothing" in my use case. – jmaculate Sep 15 '14 at 15:01
0

A notification needs to have some sort of action associated with it. You have to tell android what to do when a app user clicks the notification. Letting your library fail if no contentIntent has been defined will let your library user know that they have missed a very important step.

You could check for the pending intent before creating your notification.

if(getPendingIntentCallback != null) {
    p = getPendingIntentCallback.getPendingIntent();
    // create a notification

}
else {
    //don't create a notification
    Log.d("Notification", "Your notification was not created because no pending intent was found");
}

Or to answer the question you asked, you could create a dummy pending intent that performs some arbitrary action like going to the home screen.

See this thread: How to Launch Home Screen Programmatically in Android

Community
  • 1
  • 1
Jason Hessley
  • 1,608
  • 10
  • 8
  • I'll give you the answer because you got me started on the right train of thought. I'm going to set the `Intent` to my service and put the notification id in it as an extra, and then just cancel the notification in `onStartCommand` – Eliezer Oct 25 '12 at 02:53