尝试对空对象引用调用虚拟方法“java.lang.String android.content.Context.getSystemServiceName(java.lang.Class)”

sigwle7e  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(168)

我是Java新手,最近在尝试将一个类的一个方法访问到另一个类时遇到此错误

Attempt to invoke virtual method 'java.lang.String android.content.Context.getSystemServiceName(java.lang.Class)' on a null object reference

at android.content.ContextWrapper.getSystemServiceName(ContextWrapper.java:819)
                                                                                                        at android.content.Context.getSystemService

我有一个主类EmersysPluginPlugin

@CapacitorPlugin(name = "EmersysPlugin")
public class EmersysPluginPlugin extends Plugin {
    PushNotificationService pushNotificationService = new PushNotificationService();

    @Override
    public void load() {
        ...

        //Calling other class' method to initiate the notification channel
        pushNotificationService.createNotificationChannel();
    }
}

这是PushNotificationService

public class PushNotificationService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String token) {
       ...
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      ....
    }

    public void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           
            CharSequence name = "Test";
            String description = "Test Test";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("1", name, importance);
            channel.setDescription(description);
           
           //THE ERROR HAPPENS HERE
           //THE NotificationManager.class IS EMPTY OBJECT
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);

            Log.d("CreateNotChannel ", "Notiiftcain channel initialized");
        }
    }
}

看起来我需要初始化这个NotificationManager.class,但是不确定如何初始化。。任何帮助都是感激的。非常感谢!

xytpbqjk

xytpbqjk1#

看起来您正在引用ContextWrapper类。您需要使用上下文。

NotificationManager notificationManager = getApplicationContext().getSystemService(NotificationManager.class);

相关问题