我没有收到来自应用程序服务器的通知

时间:2018-09-22 13:09:40

标签: android firebase-cloud-messaging

从Firebase发送通知时,我会收到。但是,当我从应用服务器发送通知时,我没有收到。我的意思是,从应用服务器发送通知时,我不会通过Firebase收到通知。似乎Firebase无法检测到我的应用服务器发出的通知。

我的代码如下:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "FCM_TUI";
private String pushix = "", pushtype = "", message = "";


private int notificationId = 0;

/**
 * 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) {
    Log.i(TAG, "From: " + remoteMessage.getFrom());

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

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.i(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    //Assign the values from JSON
    try {
        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);

        pushix = object.getString("pushix");
        pushtype = object.getString("pushtype");
        message = object.getString("message");

        Variables.MESSAGE_NAME = object.optString("sendername", "");

        sendNotification(message);
    } catch (Exception e) {

    }
}
// [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 = null;

    //Setting language
    Tools.setLanguage(this);

    Variables.MESSAGE_CUSTOMER_ID = pushix;

    if (pushtype.equals("ANIM")) {

        MySharedPreferences mySharedPreferences = new MySharedPreferences();
        Variables.LANGUAGE = "&Lang=" + mySharedPreferences.loadPreferences(this, "DIL");
        Log.i("FCM_LANGUAGE", "" + Variables.LANGUAGE);
        intent = new Intent(this, MainActivity.class);
    } else if (pushtype.equals("MESSAGE")) {
        intent = new Intent(this, SendMessageActivity.class);
    } else if (pushtype.equals("WEBNOTIF") || pushtype.equals("NOTIF")) {
        intent = new Intent(this, NotificationsActivity.class);
    } else {
        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);

    //Creating the notification properties
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon_mini)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);


    //Creating the notification manager
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


    //The block which doing messagig processes
    if (!Variables.IS_MESSAGE_GONDER_OPEN) {

        notificationManager.cancel(notificationId);
        notificationId++;

        Notification notification = notificationBuilder.build();

        setBadger(notification, notificationManager);

    } else {//If the messaging page is open
        Variables.IS_MESSAGE_RECEIVED = true;

        if (!Variables.ACTIVE_MESSAGE_CUSTOMER.equals(Variables.MESSAGE_CUSTOMER_ID)) {

            notificationManager.cancel(notificationId);
            notificationId++;

            Notification notification = notificationBuilder.build();

            setBadger(notification, notificationManager);
        } else {
            updateMyActivity(getApplicationContext(), message);
        }

    }
}
/**
 * Update Activity
 *
 * @param message FCM message.
 */
static void updateMyActivity(Context context, String message) {

    Intent intent = new Intent("unique_name");

    //put whatever data you want to send, if any
    intent.putExtra("message", message);

    //send broadcast
    context.sendBroadcast(intent);
}

/**
 * Arranges the notification count and shows on app icon
 *
 * @param notification Notification.
 */
private void setBadger(Notification notification, NotificationManager notificationManager) {

    try {
        if (String.valueOf(Variables.getNotificationCount(getApplicationContext())).equals("null")) {
            Variables.setNotificationCount(getApplicationContext(), 0);
        }
    } catch (Exception e) {
        Variables.setNotificationCount(getApplicationContext(), 0);
    }
    try {
        Variables.setNotificationCount(getApplicationContext(), Variables.getNotificationCount(getApplicationContext()) + 1);
        ShortcutBadger.applyNotification(getApplicationContext(), notification, Variables.getNotificationCount(getApplicationContext()));
        notificationManager.notify(notificationId, notification);
        ShortcutBadger.applyCount(getApplicationContext(), Variables.getNotificationCount(getApplicationContext()));
    } catch (Exception e) {

    }
}

}

  

这是我上面的MyFirebaseInstanceIDService类代码:

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.
    // 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);
}

/**
 * Persist token to third-party servers.
 * <p/>
 * 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) {
    try {
        MySharedPreferences mySharedPreferences=new MySharedPreferences();
        mySharedPreferences.savePreferences(getApplicationContext(), "REGISTER TOKEN", token);
    } catch (Exception e) {
        Log.e("REG_TOKEN_ERROR", e.toString());
    }
}

}

  

我的AndroidManifest.xml代码段位于上方:

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

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

我的应用级别gradle:

 compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'org.lucasr.dspec:dspec:0.1.1'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.android.support:design:23.0.1'
compile 'com.isseiaoki:simplecropview:1.0.9'
compile 'commons-io:commons-io:2.4'
compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.android.gms:play-services:10.0.1'
compile 'com.google.android.gms:play-services-identity:10.0.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'me.leolin:ShortcutBadger:1.1.19@aar'
compile 'com.baoyz.swipemenulistview:library:1.3.0'
  

最后,我的项目级别Gradle在下面:

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

}

1 个答案:

答案 0 :(得分:0)

不是使用服务器,而是使用邮递员通过链接https://fcm.googleapis.com//fcm/send来测试通知

确保在邮递员POST请求的标头部分中添加授权和内容类型 您可以从Firebase控制台获取Firebase授权密钥

{
     "to" : "YOUR_FCM_TOKEN",
     "notification" : {
         "body" : "First Notification",
         "title": "Notificatiom Test"
     },
     "data" : {
         "body" : "First Notification",
         "title": "Notificatiom Test",
         "key1" : "Data for key1",
         "key2" : "Data for key2"
     }
    }

您可以参考https://medium.com/android-school/test-fcm-notification-with-postman-f91ba08aacc3进行参考。

成功接收到通知后,请使用服务器端的同一链接发送推送通知。

希望这会对您有所帮助。