gpt4 book ai didi

Android 为 getSystemService 获取 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 02:30:33 24 4
gpt4 key购买 nike

我想简单地创建一个 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 为 NULL

最佳答案

我想建议更好的方法,不要扩展 Activity 类,因为您需要始终启动该 Activity ,以便调用“oncreate”方法并初始化通知管理器。具有可用的应用程序上下文的单独类(在扩展应用程序的类上创建,并将其添加到应用程序标签中的 android list )。现在在该类中,将重写方法写在您想要通知的位置,例如图像通知、简单文本通知、 Action 通知。

空指针异常可能是因为您没有调用启动 Activity 。而且你的方法也不是很干净。

关于Android 为 getSystemService 获取 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27396151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com