空指针异常:在使用Firebase Messaging实现通知时发生

huangapple go评论89阅读模式
英文:

Null Pointer Exception when implementing Notifications with Firebase Messaging

问题

package com.grgsolutions.checkingin;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
    }

    public void sendNotification(Context context, String messageBody) {
        Intent intent = new Intent(context, CheckIn.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        String channelId = context.getResources().getString(R.string.new_check_in_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(context, channelId)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(context.getResources().getString(R.string.notifications_header))
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setContentIntent(pendingIntent)
                        .setSound(defaultSoundUri);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.grgsolutions.checkingin">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_launcher" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id" />

        <activity
            android:name=".SettingsActivity"
            android:label="@string/title_activity_settings" />

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713" />

        <!-- Other activity declarations -->

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_SERVICE" />
            </intent-filter>
        </service>

    </application>

</manifest>
英文:

I am implementing notifications in my app using firebase cloud messaging and following the quickstart guide provided.

I am getting a null pointer exeception on the following line of code in the MyFirebaseMessagingService.java code

I suspect the issue may be the Context being used, but I cant see that in the debugging.

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  

The following is the logcat entry

  java.lang.NullPointerException: Attempt to invoke virtual method &#39;java.lang.Object android.content.Context.getSystemService(java.lang.String)&#39; on a null object reference
at android.content.ContextWrapper.getSystemService(ContextWrapper.java:627)
at com.grgsolutions.checkingin.MyFirebaseMessagingService.sendNotification(MyFirebaseMessagingService.java:180)
at com.grgsolutions.checkingin.CheckInListAdapter$2.onClick(CheckInListAdapter.java:218)

The following is the complete MyFireBaseMessagingService.java code

package com.grgsolutions.checkingin;
/**
* Copyright 2016 Google Inc. All Rights Reserved.
* &lt;p&gt;
* Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* &lt;p&gt;
* http://www.apache.org/licenses/LICENSE-2.0
* &lt;p&gt;
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
/**
* NOTE: There can only be one service in each app that receives FCM messages. If multiple
* are declared in the Manifest then the first one will be chosen.
*
* In order to make this Java sample functional, you must remove the following from the Kotlin messaging
* service in the AndroidManifest.xml:
*
* &lt;intent-filter&gt;
*   &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot; /&gt;
* &lt;/intent-filter&gt;
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = &quot;MyFirebaseMsgService&quot;;
private String messageBody;
private Context context;
private String packageName;
private String channelId = &quot;NewCheckIn&quot;;
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages
// are handled
// here in onMessageReceived whether the app is in the foreground or background. Data
// messages are the type
// traditionally used with GCM. Notification messages are only received here in
// onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated
// notification is displayed.
// When the user taps on the notification they are returned to the app. Messages
// containing both notification
// and data payloads are treated as notification messages. The Firebase console always
// sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
Log.d(TAG, &quot;From: &quot; + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() &gt; 0) {
Log.d(TAG, &quot;Message data payload: &quot; + remoteMessage.getData());
//   if (/* Check if data needs to be processed by long running job */ true) {
//       // For long-running tasks (10 seconds or more) use WorkManager.
//       scheduleJob();
//   } else {
//       // Handle message within 10 seconds
//      handleNow();
//    }
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, &quot;Message Notification Body: &quot; + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
// [START on_new_token]
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
@Override
public void onNewToken(String token) {
Log.d(TAG, &quot;Refreshed token: &quot; + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(token);
}
// [END on_new_token]
/**
* Schedule async work using WorkManager.
*/
/*
private void scheduleJob() {
// [START dispatch_job]
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
.build();
WorkManager.getInstance().beginWith(work).enqueue();
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
/*
private void handleNow() {
Log.d(TAG, &quot;Short lived task is done.&quot;);
}
*/
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user&#39;s FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
public void sendNotification(Context context, String messageBody) {
Intent intent = new Intent (context,  CheckIn.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 , intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = context.getResources().getString(R.string.new_check_in_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(context.getResources().getString(R.string.notifications_header))
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSound(defaultSoundUri);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
&quot;Channel human readable title&quot;,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

The following is the complete AndroidManifest.xml file

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
package=&quot;com.grgsolutions.checkingin&quot;&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
--&gt;
&lt;meta-data
android:name=&quot;com.google.firebase.messaging.default_notification_icon&quot;
android:resource=&quot;@drawable/ic_launcher&quot; /&gt;
&lt;!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
--&gt;
&lt;meta-data
android:name=&quot;com.google.firebase.messaging.default_notification_color&quot;
android:resource=&quot;@color/colorAccent&quot; /&gt;
&lt;meta-data
android:name=&quot;com.google.firebase.messaging.default_notification_channel_id&quot;
android:value=&quot;@string/default_notification_channel_id&quot; /&gt;
&lt;activity
android:name=&quot;.SettingsActivity&quot;
android:label=&quot;@string/title_activity_settings&quot;&gt;&lt;/activity&gt;
&lt;meta-data
android:name=&quot;com.google.android.gms.ads.APPLICATION_ID&quot;
android:value=&quot;ca-app-pub-3940256099942544~3347511713&quot; /&gt;
&lt;activity
android:name=&quot;.Emergency&quot;
android:label=&quot;@string/title_activity_emergency&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.Contacts&quot;
android:label=&quot;@string/title_activity_contacts&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.MapsAndDirections&quot;
android:label=&quot;@string/title_activity_maps_and_directions&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.PeepsLocator&quot;
android:label=&quot;@string/title_activity_peeps_locator&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.RequestCheckIn&quot;
android:label=&quot;@string/title_activity_request_check_in&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.ViewCheckIns&quot;
android:label=&quot;@string/title_activity_view_check_ins&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.RoadTrip&quot;
android:label=&quot;@string/title_activity_road_trip&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.Commute&quot;
android:label=&quot;@string/title_activity_commute&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.Settings&quot;
android:label=&quot;@string/title_activity_settings&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.CheckIn&quot;
android:label=&quot;@string/title_activity_check_in&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.CheckInNew&quot;
android:label=&quot;CheckInNew&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot; /&gt;
&lt;activity
android:name=&quot;.MainActivity&quot;
android:label=&quot;@string/app_name&quot;
android:theme=&quot;@style/AppTheme.NoActionBar&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;service
android:name=&quot;.MyFirebaseMessagingService&quot;
android:exported=&quot;false&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;com.google.firebase.MESSAGING_SERVICE&quot;/&gt;
&lt;/intent-filter&gt;
&lt;/service&gt;
&lt;/application&gt;
&lt;/manifest&gt;
</details>
# 答案1
**得分**: 1
NotificationManager notificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)
<details>
<summary>英文:</summary>
NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)
</details>

huangapple
  • 本文由 发表于 2020年3月16日 21:53:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/60707279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定