FirebaseMessagingService在应用关闭时拦截通知

时间:2018-03-16 13:16:27

标签: android notifications firebase-cloud-messaging intercept

我可以在关闭应用时拦截通知吗? 我需要使用此库ShortcutBadger

设置徽章

感谢。

3 个答案:

答案 0 :(得分:0)

你的意思是吗?

public class AppFcmMessagingsService extends FirebaseMessagingService {

private static final String TAG = "FirebaseMessageService";

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    try {
        if(remoteMessage.getData().size() > 0) {

            final JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString());
            Log.d(TAG,"remoteMessage = " + jsonObject.toString());
            int badgeCount = 1;
            ShortcutBadger.applyCount(getApplicationContext(), badgeCount); 
        }
    } catch (Exception e) {
        Log.e(TAG, "onMessageReceived: ", e);
    }
    if(remoteMessage.getNotification() != null) {
            int badgeCount = 1;
            ShortcutBadger.applyCount(getApplicationContext(), badgeCount); 
             Log.d(TAG, "notification body : " + remoteMessage.getNotification().getBody());
    }
}
}

答案 1 :(得分:0)

有三种类型的通知:

通知:可以从Web控制台或任何后端发送,它已预定义值。如果应用程序处于打开状态,则可以在onMessageRecieve上自定义行为,如果应用程序已关闭,则会触发默认通知。 data:一个键值对,只有字符串。可以从任何后端发送。行为始终在onMessageReceived方法中定义。 通知和数据:先前的组合将具有通知的行为,一旦在默认启动器活动中单击通知,数据将作为附加提供。可以从Web控制台或任何后端发送。

push是一个名为Payload的json,它包含这些对象:

有效负载:{     数据:{...} }

是的,您可以向自己发送数据类型通知,它将始终执行您在MessagingService内的onMessageReceived方法中所写的内容。

此文档可以帮助您 https://firebase.google.com/docs/cloud-messaging/concept-options?hl=es-419

如果您没有服务器,请使用功能。

由于默认通知不会显示,您可能希望显示自己的通知。 如果您还想显示通知,则必须从onMessageReceived内部调用NotificationCompat类。视觉通知与推送消息无关,事实上,可以通过按下按钮来触发视觉通知。

要创建可视通知,最好的方法是让Android Studio为您完成。再次单击您的活动.java所在的包,新的,然后是selecet ui-component,并且有通知。它将创建通知的基本模板。然后在onMessaReceived中使用那些方法,将必须显示的信息传递给用户。

关于班级的文档 https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

你可能会发现这个错误 NotificationCompat.Builder deprecated in Android O

答案 2 :(得分:0)

万一您从未解决过此问题,问题不在于您如何在应用程序中实现它,而在于如何发送JSON数据有效载荷。请参阅this question及其相应的答案,以了解为何在后台时没有收到消息。

非常简短的摘要是,如果您收到notification有效负载,则它将从不在后台触发。如果您收到data有效载荷而没有 notification,则可以在应用程序处于后台时进行解析并执行操作。