繁体   English   中英

Android:即使触发了onMessageReceived方法,也未收到Firebase推送通知

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

我首先要说我是Android开发的一个完整的初学者。 我试图创建一个基本应用程序来更新FIrebase数据库中的值。 数据库工作正常,但是,每次数据库中的值更改时,我都希望收到通知。 因此,我尝试使用Firebase的Cloud Messaging Service。 我根据文档进行了设置,并决定通过Firebase控制台发送消息来测试通知。 发送消息时,它将被记录在控制台中,这必须表示正在触发onMessageReceived()方法。 但是,在模拟器或真实设备上进行测试时,该通知均不会出现。 下面是代码:

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>

摇篮

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'

安慰

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

编辑1

我通过添加通知通道更改了MyFirebaseMessagingService.java中sendNotification()方法的代码。 我使用Android M(API级别23)制作了另一个设备模拟器,并且当应用程序处于前台时,通知会显示在其上。 但是,当我在也是Android M的实际设备上尝试该操作时,不会出现通知。 更改后的代码如下:

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());
}

将依赖项放入Project gradle文件中:

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

将依赖项放入应用gradle文件中:

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

并将其放入依赖关系块的应用程序gradle文件中

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

并将服务放在AndroidManifest.xml文件中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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