Android not receiving Firebase Push Notification -

2019-01-29 02:17发布

I'm trying to work on a messenger app, but the twist here is I have 2 Entities (i.e. 2 apps A & B) here.

Now I'm trying to put messaging logic between the two using Firebase. Firebase doesn't support communication between two different applications (A & B) over the same project url. In order to overcome that restriction, I have used the same google-service.json of app A for app B as well.

For app B, I have just changed the project id and auth key. That seems to have worked as I intended. I have tested the push notification as well using the Firebase Console and it seemed to have been working.

Then I have tried to implement the server logic. To make one-on-one notification.

CASE 1

But the problem arises here is that from app B, if I send a notification request, I get a MismatchSenderId error where the project id has not been tempered with.

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

CASE 2

and for app A, here is the following response I get:

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

For this, the success value is 1 hence, the notification should be sent but it's not sending when I'm making the request from the device. But it works flawlessly when I perform the same server call using Postman or any other client.

Here are my codes 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());
}
}

And here is the declaration in the Manifest.xml within Application tag

 <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

CASE 1 Solved

I have managed to solve CASE 1 where for B I had to use the server api key of B , similarly for A

EDIT 2

Added Server side code

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

2条回答
Fickle 薄情
2楼-- · 2019-01-29 02:39

Edit #1:

1) Make sure you are sending a valid json to the fcm. 2) Make sure you are sending to the right token.

Other informations on how to send notifications:

Send messages to specific devices

To send messages to specific devices, set the to the registration token for the specific app instance

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

Send messages to topics

here the topic is : /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

Send messages to device groups

Sending messages to a device group is very similar to sending messages to an individual device. Set the to parameter to the unique notification key for the device group

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

Original:

The problem is you server configuration. If you want to manage two firebase apps in single server you have you have to config two firebase apps with your Firebase APK_KEY that located at:

Go to your applications in Firebase console -> Click on three dots at the top right -> Manage -> CLOUD MESSAGES -> (Server key)

After you get your both server keys for your two apps, you have to configure it like this:

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
查看更多
Explosion°爆炸
3楼-- · 2019-01-29 02:53

I fixed error MismatchSenderId

Example, below:

valid token: cwsm26j-8qM:APA91bEGbg5xxxxxxxxxxxxxxxxxxxxxx

invalid token: APA91bEGbg5xxxxxxxxxxxxxxxxxxxxxx

查看更多
登录 后发表回答