3

I have a service running in the background and I want to notify user if there is a new data, I've used a notificationmanager, and the notification appears, but when clicking on it it doesn't do anything (it is supposed to show an activity I'm new in android and here is my code

NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = newNotification(R.drawable.shoppingcarticon, "Nouvelle notification de ShopAlert", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(this,GooglemapActivity.class);
PendingIntent activity = PendingIntent.getService(this, 0, intent, 0);

notification.setLatestEventInfo(this, "This is the title", "This is the text", activity);
notification.number += 1;
notificationmanager.notify(0, notification);

your help will be appreciated.

Clément Jean
  • 1,735
  • 1
  • 14
  • 32
Yasmine GreenApple
  • 438
  • 1
  • 5
  • 15

2 Answers2

6

You can use this code. Change Main.Class to your activity class, And Title and content text as you need them.

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);


int icon = R.drawable.ic_action_search;
CharSequence tickerText = "Pet Parrot";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Context context = getApplicationContext();
CharSequence contentTitle = "Hungry!";
CharSequence contentText = "your parrot food meter is: ";
Intent notificationIntent = new Intent(context, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

mNotificationManager.notify(1, notification); // Log.d("test", "Saving Data to File from Service.");
Clément Jean
  • 1,735
  • 1
  • 14
  • 32
Waqas
  • 4,411
  • 6
  • 27
  • 31
3

The following line:

PendingIntent activity = PendingIntent.getService(this, 0, intent, 0);

should look this way:

PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);

since you're trying to start an Activity, not a Service. Hope this helps.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • thank you for you help, but it doesn't work too, the notification text doesn't show (in a normal state, when I click I have the notification bar with my notification, but here the notification bar is empty) – Yasmine GreenApple Jul 22 '12 at 10:40
  • @Yasmine GreenApple, Make sure the code is indeed executed. And by the way the Notification initialization mode you're using is deprecated, take a look at Notification.Builder class as it's the preferred way for constructing notifications now. – Egor Jul 22 '12 at 11:42