Мое приложение аварийно завершает работу при получении уведомления через FCM - PullRequest
0 голосов
/ 25 апреля 2019

Я использую облачные сообщения Firebase для получения push-уведомлений.Работало нормально.Но теперь, когда приложение получает данные уведомления, происходит сбой и даже не отображается номер строки, в которой происходит сбой.

Я уже проверил код класса FirebaseMessagingService моего другого приложения, в котором служба уведомленийработает отлично.

В журналах отображается следующая ошибка

E/AndroidRuntime: FATAL EXCEPTION: Firebase-WrappedFirebaseMessagingService
Process: net.eazypg.eazypgtenant, PID: 16823
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
    at com.google.firebase.messaging.zzb.<init>(Unknown Source:5)
    at com.google.firebase.messaging.FirebaseMessagingService.zzd(Unknown Source:58)
    at com.google.firebase.iid.zzb.run(Unknown Source:2)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source:6)
    at java.lang.Thread.run(Thread.java:764)

Мой класс Firebase Messeging:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private NotificationManager notifManager;
private NotificationChannel mChannel;

FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
FirebaseUser firebaseUser;
DatabaseReference databaseReference;

@Override
public void onNewToken(String s) {
    super.onNewToken(s);

    sendRegistrationToServer(s);

}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    Map<String, String> data = remoteMessage.getData();

    pushNotification(data.get("title"),
                        data.get("body"),
                        data.get("imageUrl"),
                        data.get("click_action"));

}

private void pushNotification(String title, String body, String imageUrl, String clickAction) {

    Intent intent;
    PendingIntent pendingIntent;
    NotificationCompat.Builder builder;

    if (notifManager == null) {
        notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    intent = new Intent(clickAction);
    intent.setAction(Long.toString(System.currentTimeMillis()));

    int uniqueInt = (int) (System.currentTimeMillis() & 0xfffffff);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


        if (mChannel == null) {
            NotificationChannel mChannel = new NotificationChannel("0", title, NotificationManager.IMPORTANCE_DEFAULT);
            mChannel.setDescription (body);
            mChannel.enableVibration (true);
            mChannel.setVibrationPattern (new long[] {100, 200, 300, 400, 300, 200, 400});
            notifManager.createNotificationChannel (mChannel);
        }

        builder = new NotificationCompat.Builder (this, "0");

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentTitle(title)  // flare_icon_30

                .setSmallIcon(R.drawable.notification)
                .setContentText(body)
                .setDefaults(Notification.DEFAULT_ALL)
                .setAutoCancel(true)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon_logo))
                .setBadgeIconType(R.drawable.icon_logo)
                .setContentIntent(pendingIntent)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setVibrate(new long[]{100, 200, 300, 400, 300, 200, 100, 300});

    } else {

        builder = new NotificationCompat.Builder(this, "0");

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentTitle(title)
                .setSmallIcon(R.drawable.icon_logo) // required
                .setContentText(body)  // required
                .setDefaults(Notification.DEFAULT_ALL)
                .setAutoCancel(true)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon_logo))
                .setContentIntent(pendingIntent)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setVibrate(new long[]{100, 200, 300, 400, 300, 200, 100, 300})
                .setPriority(Notification.PRIORITY_HIGH);
    }

    Notification notification = builder.build ();
    notifManager.notify (0, notification);

}

} Я уже инициализировал все необходимое в манифестефайл

<meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />

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

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

Большое спасибо заранее!

1 Ответ

0 голосов
/ 25 апреля 2019

попробуйте обновить ваш gradle с помощью самой последней базы сообщений Firebase

implementation 'com.google.firebase:firebase-messaging:17.5.0'

вот аналогичная проблема сбой приложения при получении уведомления

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...