我想简单地创建一个Android通知类,以便在任何地方使用它,但是在这段代码中,我得到了notificationManager变量的NullPointerException错误:
public class TsNotify extends Activity {
private NotificationManager notificationManager;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
notificationManager = (NotificationManager) getSystemService ( Context.NOTIFICATION_SERVICE );
}
public void notify( String title ) {
...
notificationManager.notify ( NOTIFICATION_ID, notification );
}
}我将其更改为以下行,但此问题不能解决:
notificationManager = (NotificationManager) this.getSystemService ( Context.NOTIFICATION_SERVICE );或
notificationManager = (NotificationManager) getBaseContext().getSystemService ( Context.NOTIFICATION_SERVICE );notificationManager为空
发布于 2014-12-10 16:35:38
我建议更好的方法,不要扩展activity类,因为你需要总是启动那个activity,这样你的"oncreate“方法就会被调用,通知管理器会被初始化。有单独的类和应用程序上下文可用(在类扩展应用程序上创建,并在应用程序标签中添加android清单)。现在在这个类中,在你想要通知的地方编写覆盖的方法,比如图像通知,或者简单的文本通知,动作通知。
空指针异常可能是因为您未调用启动活动。而且你的方法也不是很干净。
https://stackoverflow.com/questions/27396151
复制相似问题