Sending a notification from a service in Android

e-satis picture e-satis · Jul 30, 2009 · Viewed 147.8k times · Source

I have a service running, and would like to send a notification. Too bad, the notification object requires a Context, like an Activity, and not a Service.

Do you know any way to by pass that ? I tried to create an Activity for each notification but it seems ugly, and I can't find a way to launch an Activity without any View.

Answer

Josef Pfleger picture Josef Pfleger · Jul 30, 2009

Both Activity and Service actually extend Context so you can simply use this as your Context within your Service.

NotificationManager notificationManager =
    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);