问题
I am unable to generate the notification (in the notification area) from an IntentService. I get a NullPointerException while obtaining NotificationManager. The problem is with Context.
06-01 16:46:05.910: ERROR/AndroidRuntime(14745): Caused by: java.lang.NullPointerException
06-01 16:46:05.910: ERROR/AndroidRuntime(14745): at android.content.ContextWrapper.getSystemService(ContextWrapper.java:363)
06-01 16:46:05.910: ERROR/AndroidRuntime(14745): at com.Android.Main1.FileUploaderService.<init>(FileUploaderService.java:71)
The line of code is:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
I have tried getApplicationContext(), getBaseContext(), but to no avail.
Could someone please let me know what is the problem here? How do I generate notifications from an IntentService?
Additional Info:
I also have a Service in my app, and notifications from there work properly. The IntentService is not started by an Activity; it is started by the Service.
回答1:
Move your call to getSystemService out of the constructor and into onCreate.
The base Context in the ContextWrapper has not been set yet, which is causing the NullPointerException.
来源:https://stackoverflow.com/questions/6207689/notification-from-intentservice-nullpointerexception-while-obtaining-context