Notification from IntentService - NullPointerException while obtaining Context

青春壹個敷衍的年華 提交于 2019-12-01 15:27:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!