【问题标题】:Android not receiving Firebase Push Notification - MismatchSenderIdAndroid 未收到 Firebase 推送通知 - MismatchSenderId
【发布时间】:2016-09-12 06:38:00
【问题描述】:

我正在尝试开发一个信使应用程序,但这里的转折是我在这里有 2 个实体(即 2 个应用程序 A 和 B)。

现在我正在尝试使用 Firebase 在两者之间放置消息传递逻辑。 Firebase 不支持两个不同的应用程序(A 和 B)通过同一个 项目 url 进行通信。为了克服这个限制,我也为应用 B 使用了与应用 A 相同的 google-service.json

对于应用 B,我刚刚更改了项目 idauth key。这似乎按我的预期工作。我也使用 Firebase 控制台测试了推送通知,它似乎一直在工作。

然后我尝试实现服务器逻辑。发出一对一通知。

案例 1

但这里出现的问题是,从应用程序 B 中,如果我发送通知请求,我会收到 MismatchSenderId 错误,其中项目 id 没有经过调整。

{"multicast_id":[removed],"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

案例 2

对于应用 A,我得到以下响应:

{"multicast_id":[removed],"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1473661851590851%0e4bcac9f9fd7ecd"}]}

为此,成功值为1,因此,应该发送通知,但当我从设备发出请求时它没有发送。但是当我使用 Postman 或任何其他客户端执行相同的服务器调用时,它可以完美运行。

这是我的代码MyFirebaseInstanceIDService.java

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";
private static final String FRIENDLY_ENGAGE_TOPIC = "friendly_engage";


@Override
public void onCreate() {
    String savedToken = Utility.getFirebaseInstanceId(getApplicationContext());
    String defaultToken = getApplication().getString(R.string.pref_firebase_instance_id_default_key);
    Log.d("GCM", savedToken);
    if (savedToken.equalsIgnoreCase(defaultToken))
    //currentToken is null when app is first installed and token is not available
    //also skip if token is already saved in preferences...
    {
        String CurrentToken = FirebaseInstanceId.getInstance().getToken();
        if (CurrentToken != null)
            Utility.setFirebaseInstanceId(getApplicationContext(), CurrentToken);
        Log.d("Value not set", CurrentToken);
        updateFCMTokenId(CurrentToken);
    }
    super.onCreate();
}

/**
 * The Application's current Instance ID token is no longer valid
 * and thus a new one must be requested.
 */
@Override
public void onTokenRefresh() {
    // If you need to handle the generation of a token, initially or
    // after a refresh this is where you should do that.
    String token = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "FCM Token: " + token);
    Utility.setFirebaseInstanceId(getApplicationContext(), token);
    updateFCMTokenId(token);
}

private void updateFCMTokenId(final String token) {
    SQLiteHandler db = new SQLiteHandler(getBaseContext());
    final HashMap<String, String> map = db.getUserDetails();
    //update fcm token for push notifications
    StringRequest str = new StringRequest(Request.Method.POST, AppConfig.UPDATE_GCM_ID, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            Log.d("GCM RESPONSE", response);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> param = new HashMap<>();
            param.put("user_id", map.get("uid"));
            param.put("gcm_registration_id", token);
            return param;
        }
    };
    str.setShouldCache(false);
    str.setRetryPolicy(new DefaultRetryPolicy(AppConfig.DEFAULT_RETRY_TIME, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    AppController.getInstance().addToRequestQueue(str);
}

}

FirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    //Displaying data in log
    //It is optional
    try {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().get("message"));
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Calling method to generate notification
    sendNotification(remoteMessage.getData().get("message"));
}

//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, ChatRoomActivity.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);
    android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("NAME")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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

这是Application标签内Manifest.xml中的声明

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

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

TIA

案例 1 已解决

我已经设法解决了案例 1,对于 B 我必须使用 B 的服务器 api 密钥,对于 A 类似

编辑 2

添加服务器端代码

public function sendNotification($message, $gcm_id, $user_level)
{
    if ($user_level == "level") {
        $server_key = "xys";
    } else  $server_key = "ABC";
    $msg = array
    (
        'message' => $message,
        'title' => 'Title',
        'vibrate' => 1,
        'sound' => 1,
        'largeIcon' => 'large_icon',
        'smallIcon' => 'small_icon'
    );
    $fields = array
    (
        'to' => $gcm_id,
        'data' => $msg
    );


    $headers = array
    (
        'Authorization: key=' . $server_key,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    curl_close($ch);
    echo $result;
}

【问题讨论】:

  • 我不清楚“App A 和 App B”的事情。它们是来自两个不同项目的两个不同应用程序吗?或者,它们只是同一项目的两个不同实例? For app B, I have just changed the project id and auth key - 让我感到困惑!
  • @SudipPodder 他们是两个不同的项目
  • 您能否附上您从设备发出的 httppost 请求?
  • @SudipPodder 来自客户端我正在使用 volley 请求上述服务器端代码

标签: android firebase firebase-cloud-messaging firebase-notifications


【解决方案1】:

编辑#1:

1) 确保向 fcm 发送有效的 json。 2) 确保您发送到正确的令牌。

关于如何发送通知的其他信息:

向特定设备发送消息

要将消息发送到特定设备,请将 设置为特定应用实例的注册令牌

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send

向主题发送消息

这里的主题是:/topics/foo-bar

curl -H "Content-type: application/json" -H "Authorisation:key=<Your Api key>"  -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send

向设备组发送消息

向设备组发送消息与向单个设备发送消息非常相似。将 to 参数设置为设备组的唯一通知键

curl -H "Content-type: application/json" -H "Authorisation:key=<Your Api key>"  -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send

原文:

问题是你的服务器配置。如果您想在单个服务器中管理两个 Firebase 应用程序,您必须使用位于以下位置的 Firebase APK_KEY 配置两个 Firebase 应用程序:

在 Firebase 控制台中转到您的应用程序 -> 点击右上角的三个点 -> 管理 -> CLOUD MESSAGES ->(服务器密钥)

获得两个应用程序的两个服务器密钥后,您必须像这样配置它:

var firebaseLib = require("firebase");

var app1Config = {
    apiKey: "<PROJECT_1_API_KEY>",
    authDomain: "<PROJECT_1_ID>.firebaseapp.com",
    databaseURL: "https://<PROJECT_1_DATABASE_NAME>.firebaseio.com",
    storageBucket: "<PROJECT_1_BUCKET>.appspot.com",
}
var app2Config = {
    apiKey: "<PROJECT_2_API_KEY>",
    authDomain: "<PROJECT_2_ID>.firebaseapp.com",
    databaseURL: "https://<PROJECT_2_DATABASE_NAME>.firebaseio.com",
    storageBucket: "<PROJECT_2_BUCKET>.appspot.com",
}

var firebaseApp1 = firebaseLib.initailize(app1Config); // Primary
var firebaseApp2 = firebaseLib.initailize(app2Config, "Secondary"); // Secondary

【讨论】:

  • 请检查我更新的问题。我已经设法通过根据应用程序更改服务器密钥来使应用程序工作,但是当从设备发送请求时它不会工作
  • 我没有看到任何从设备发送到通知的请求,你能在这里发布你的代码
  • 我正在向应用服务器请求推送通知
  • 为什么不使用 firebase nodejs fcm 模块?
  • 对不起!我不知道...服务器只处理 php
【解决方案2】:

我修复了错误 MismatchSenderId

示例,如下:

有效令牌:cwsm26j-8qM:APA91bEGbg5xxxxxxxxxxxxxxxxxxxxxxxx

无效令牌:APA91bEGbg5xxxxxxxxxxxxxxxxxxxxxx

【讨论】:

  • 请描述您的解决方案,因为上述答案没有给出清晰的理解
  • 我认为错误的原因是由于android应用程序从firebase devicetoken获取时没有获得令牌的第一部分
猜你喜欢
  • 2020-08-02
  • 1970-01-01
  • 2022-07-27
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2015-02-09
相关资源
最近更新 更多