简体   繁体   中英

Android : Firebase push notification not received even though onMessageReceived method is triggered

I should start by saying that I am a complete beginner in Android Development. I am attempting to create a basic application which updates values in a FIrebase Database. The database is working correctly, however, I wanted to receive a notification every time a value was changed in the database. So I attempted to use Firebase's Cloud Messaging Service. I set it up according to the documentation and decided to test the notification by sending a message through the Firebase console. When the message is sent, it gets logged in the console which must mean that onMessageReceived() method is being triggered. However, the notification doesn't appear when tested on either a simulator or a real device. Below is the code:

MyFirebaseMessagingService.java

package com.example.rohit.a2175;

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.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

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

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("FCM Message")
                    .setContentText(messageBody)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    notificationManager.notify(0, notificationBuilder.build());
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rohit.a2175">

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<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">
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
        android:theme="@style/Base.Theme.AppCompat" />
    <activity
        android:name=".Image"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_image"
        android:theme="@style/FullscreenTheme"></activity>
    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
</application>

</manifest>

Gradle

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
    applicationId "com.example.rohit.a2175"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', 
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:design:26.+'
compile 'com.android.support:support-vector-drawable:26.+'
compile 'com.google.firebase:firebase-database:9.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-storage:9.4.0'
compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.5.+'
compile 'com.android.support:support-v4:26.+'
compile 'com.google.firebase:firebase-messaging:9.4.0'
testCompile 'junit:junit:4.12'
}


apply plugin: 'com.google.gms.google-services'

Console

11-07 00:46:34.845 5030-5747/com.example.rohit.a2175 D/MyFirebaseMsgService: Message Notification Body: Test Message

Edit 1

I changed the code for the sendNotification() method in MyFirebaseMessagingService.java by adding a notification channel. I made another device emulator with Android M (API level 23) and the notification is appearing on it when the application is in the foreground. However, when I try this on my actual device which is also Android M, the notification doesn't appear. The changed code is below :

public void sendNotification(String messageTitle,String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setVibrate(new long[]{0, 100, 100, 100, 100, 100})
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(messageTitle)
            .setContentText(messageBody);

    notificationManager.notify(0, builder.build());
}

put dependencies in Project gradle file :

classpath 'com.google.gms:google-services:3.0.0'

put dependencies in app gradle file :

compile 'com.google.firebase:firebase-messaging:10.2.1'

and put this in app gradle file in blow of dependencies block

apply plugin: 'com.google.gms.google-services'

and put service in AndroidManifest.xml file :

    <service
        android:name=".services.MyFcmListenerService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM