Firebase云消息传递无法工作。

7

我想在我的应用程序中显示通知。我在Firebase控制台上创建了一个应用程序。注意:没有错误。当应用程序启动后,从Firebase控制台发送消息后,什么也没有出现。这里有什么问题?

MyFireBaseInstaceIDService.java

package com.example.hp.mesajlasma;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";

/**
 * 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.
 */
// [START refresh_token]
@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // 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(refreshedToken);
}
// [END refresh_token]

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user'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.
}
}

MyFireBaseMessagingService.java

package com.example.hp.mesajlasma;

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;

/*** Created by Belal on 5/27/2016.*/

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * 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]

    Log.d(TAG, "From: " + remoteMessage.getFrom());

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

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + 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]

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
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 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark_focused)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.


buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0-alpha5'
    classpath 'com.google.gms:google-services:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

AndroidManifest

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

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


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

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

    <service
        android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</application>

</manifest>

build.gradle(应用程序)

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "24.0.0"
defaultConfig {
    applicationId "com.example.hp.mesajlasma"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
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:23.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha5'
testCompile 'junit:junit:4.12'
compile 'com.google.firebase:firebase-messaging:9.0.0'
}
apply plugin: 'com.google.gms.google-services'

看一下这个链接,如果它能让你的应用程序正常接收通知,请接受答案。http://stackoverflow.com/questions/37997957/fcm-not-receiving-notifications-when-the-app-is-relaunched/37998202#37998202 - CodeDaily
我已经添加了权限,但它仍然无法工作。这让我很疯狂... - Hüseyin YILMAZ
你是否将 google-services.json 文件添加到你的项目中了? - Machado
你从控制台中使用了什么作为目标?你尝试过发送到由 Firebase Messaging 生成的 Instance ID 令牌吗?另外,我建议使用 v9.4.0。 - Arthur Thompson
你是否找到了解决方案? - JohnA10
4个回答

2

除了MyFireBaseMessaginService.java文件之外,所有文件看起来都很好。将其与我的进行比较并进行更改,它应该可以工作。

package biz.coolpage.rjabhi.tesstingfcm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.RemoteMessage;

/**
 * Created by Warrior on 8/8/2016.
 */
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService
{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        showNotification(remoteMessage.getData().get("message"));
    }

    private void showNotification(String message) {
        Intent i=new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle("FCM TITLE").setContentText(message)
                .setSmallIcon(R.drawable.ic_launcher)
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0,builder.build());
    }
}

请确保您已在FCM控制台注册了应用程序,并在输入应用程序包名称后生成了googleservices.json文件。

MainActivity.java

package biz.coolpage.rjabhi.tesstingfcm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseMessaging.getInstance().subscribeToTopic("test");
        FirebaseInstanceId.getInstance().getToken();
        Log.d("TOKEN",FirebaseInstanceId.getInstance().getToken());
    }
}

FireBaseInstanceIDService.java

package biz.coolpage.rjabhi.tesstingfcm;

import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.google.firebase.iid.FirebaseInstanceId;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Warrior on 8/8/2016.
 */
public class FirebaseInstanceIDService extends com.google.firebase.iid.FirebaseInstanceIdService
{
    @Override
    public void onTokenRefresh() {
        String token= FirebaseInstanceId.getInstance().getToken();
        Log.d("GOT TOKEN: ",token);
        registerToken(token);
    }

    private void registerToken(String token) {
//code to save token
    }
}

它不起作用。我的MainActivity.java是空的,没有任何代码。MainActivity.java文件中有任何代码吗? - Hüseyin YILMAZ
检查一下你的Logcat。你在那里得到Token了吗? 看起来这只是GooGleQuickStart的示例项目?如果是这样,请确保在FCM控制台上注册项目,并获取自己的googleservices.json,然后将其粘贴到项目的应用程序目录中。 - Raj
当我发送一条消息时,它会给出这个。 - Hüseyin YILMAZ
08-09 17:10:50.807 3163-3189/com.example.hp.mesajlasma W/InstanceID/Rpc: 无法解析REGISTER意图,回退 08-09 17:10:50.811 3163-3189/com.example.hp.mesajlasma W/InstanceID/Rpc: Google Play服务和旧版GSF包均缺失 08-09 17:10:50.811 3163-3179/com.example.hp.mesajlasma I/FA: 将此实例标记为上传者 - Hüseyin YILMAZ
你是使用模拟器还是安卓手机等设备来运行应用程序?"08-09 17:10:50.807 3163-3189/com.example.hp.mesajlasma W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back 08-09 17:10:50.811 3163-3189/com.example.hp.mesajlasm..." 这就是你的日志记录吗? - Raj
显示剩余2条评论

0

简化Firebase通知的过程。

从以下链接下载示例代码:

https://github.com/firebase/quickstart-android (它是100%有效的)

进行通知测试:

进入Firebase控制台 -> 选择您的应用程序

选择“通知”部分 -> 点击“新消息”,添加您的消息,然后点击“发送消息”。


0

关于设置 FCM,如 设置 Firebase 和 FCM SDK 所述,第一步是将 Firebase 添加到您的 Android 项目中(添加 Firebase 到您的 Android 项目)

如果您已经按照所有其他添加 Firebase 到应用程序的步骤进行操作,则可能需要添加compile 'com.google.firebase:firebase-core:9.4.0'(适当的版本,例如 9.0 如果您喜欢旧版本,以确保一致性,我包括了最新版本)。


0
只需将 Firebase Messaging 导入您的项目中。 您需要在 app 模块 gradle 文件中添加此行。
//Add this line firebase
    compile 'com.google.firebase:firebase-messaging:9.0.0'
    /

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接