This is confusing. I'm look at the Android 2.2.2_r1 source code for the NotificationManager class, and I see the method getService()
which is defined as public
and static
. However, eclipse is telling me:
The method getService() is undefined for the type NotificationManager on the line
Object o = NotificationManager.getService();
My project is building against Android 2.2/ API Level 8. I tried to use reflection to see the method names and modifiers, and sure enough, I got back
public static getService
Am I missing something here? Why would eclipse tell me this method doesn't exist?
The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
Use public static methods if the method can be considered a unit, and can be effectively tested on its own. It's plain hard to implement dependency injection or mocks on types that use static method. I use static methods for utility methods with few/no dependencies, and well defined input/output.
No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.
You will find a very detailed answer in this post.
In short: Because you compile against the android.jar
, which has all hidden methods (like the one you are trying to access) removed. They will only be there on runtime, for internal android usage.
But since you perhaps also need it. The right way to access the NotificationManager
is via the getSystemService
method of a context:
NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
With context
being a valid context (like your current activity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With