当我在前台发送带有数据有效负载的通知消息时,我的应用程序崩溃。当它处于后台或已终止状态时,它可以正常运行,但为什么不能在前景上运行?
这是错误:
java.lang.NullPointerException 在... MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:57)
,错误表示,该行在MyFirebaseMessagingService中给出:
if(dataType.equals(getString(R.string.direct_message))){
编译器已经发现了问题,并显示:
方法调用“等于”可能会产生“ java.lang.NullPointerException”
这是 Firebase Messaging Service 类的一小部分:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static final int BROADCAST_NOTIFICATION_ID = 1;
@Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String notificationBody = "";
String notificationTitle = "";
String notificationData = "";
try{
notificationData = remoteMessage.getData().toString();
notificationTitle = remoteMessage.getNotification().getTitle();
notificationBody = remoteMessage.getNotification().getBody();
}catch (NullPointerException e){
Log.e(TAG, "onMessageReceived: NullPointerException: " + e.getMessage() );
}
Log.d(TAG, "onMessageReceived: data: " + notificationData);
Log.d(TAG, "onMessageReceived: notification body: " + notificationBody);
Log.d(TAG, "onMessageReceived: notification title: " + notificationTitle);
String dataType = remoteMessage.getData().get(getString(R.string.data_type));
if(dataType.equals(getString(R.string.direct_message))){
Log.d(TAG, "onMessageReceived: new incoming message.");
String title = remoteMessage.getData().get(getString(R.string.data_title));
String message = remoteMessage.getData().get(getString(R.string.data_message));
String messageId = remoteMessage.getData().get(getString(R.string.data_message_id));
sendMessageNotification(title, message, messageId);
}
}
}
我猜(getString(R.string.direct_message)
为空,但我不知道为什么前台它为空。我该如何解决这个问题?