13
package com.test.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class runOnBoot extends BroadcastReceiver{

   @Override
   public void onReceive(Context context, Intent intent) {

          NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
   }
}

When I try to build the package, it says

compile:
    [javac] Compiling 2 source files to /home/mrburns/Desktop/myapp/bin/classes
    [javac] /home/mrburns/Desktop/myapp/src/com/test/app/runOnBoot.java:14: cannot find symbol
    [javac] symbol  : variable NOTIFICATION_SERVICE
    [javac] location: class runOnBoot
    [javac]           NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    [javac]                                                                                           ^
    [javac] 1 error

BUILD FAILED
Linh
  • 57,942
  • 23
  • 262
  • 279
mrburns
  • 453
  • 1
  • 8
  • 17

6 Answers6

29

I found calling this way works:

NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mcchots
  • 503
  • 9
  • 16
9

This should be Context.NOTIFICATION_SERVICE:

NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Shlublu
  • 10,917
  • 4
  • 51
  • 70
  • I see that is answer is currently being downvoted while it wasn't before. As it has been written in 2011, I suspect that some API updates make it deprecated though I didn't have time to check. – Shlublu Jun 29 '21 at 15:40
2

For those using Kotlin, the following line performs the same functionality as the other answers here.

val nm = context?.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
RustinH
  • 21
  • 2
0
NotificationManager mNotifyMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Linh
  • 57,942
  • 23
  • 262
  • 279
  • In addition to your code please add some text to explain why your answer works or how it is different from previous answers. – buczek Oct 20 '16 at 14:10
0

This should be

notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
-2

You should better try this

 NotificationManager nm = (NotificationManager)getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
Shah
  • 4,990
  • 10
  • 48
  • 70
  • NOTIFICATION_SERVICE is a `public static final String`. You do not need any instance of `Context` to use it. – Shlublu Jul 27 '11 at 12:21
  • it can be accessed in both ways :) If you are displaying the notification in Any web Service not in activity then you dont have the Context with you :) – Shah Jul 29 '11 at 06:14
  • You don't need any instance of Context. You statically call it from the class Context. – Shlublu Jul 29 '11 at 06:26