【问题标题】:Android Notifications with customized appearance具有自定义外观的 Android 通知
【发布时间】:2018-04-24 06:28:10
【问题描述】:

到目前为止,我正在使用 Firebase 云消息传递作为我应用的通知系统。据我了解,即使是最大的公司也使用 GCM,现在正在被 FCM 取代。但是,我被作为“通知”有效负载发送的限制所困。

Firebase 在 OnMessageRecieved 中接收 data 消息,我可以通过使用它来获得我想要的确切行为。然而,在过去的三个月里,我注意到我的应用程序的通知根本不起作用,因为当应用程序处于后台/非活动状态时没有收到数据有效负载。这非常令人沮丧,因为我发现实际发送提醒用户的通知的唯一解决方法是通过发送 notification 有效负载。

我不知道如何使用通知负载来获得我想要的行为,就像我使用数据负载一样,但我意识到,当应用程序处于前台时,让通知完美显示是没有意义的,如果它们不显示在应用在后台时。

我想知道的是,如果有人可以推荐一种以我想要的样式而不是默认的 Firebase 通知 样式显示通知的方法,并且我真的很感激指导。详细说明一下,我目前有一个功能齐全的系统,允许用户通过通知响应消息,而无需打开应用程序,但只能通过 data 有效负载。

我知道有一种方法可以在应用处于后台或未运行时以自定义方式发送通知(添加意图、按钮等),因为这是由 Facebook、WhatsApp 和市场。我知道一种叫做 AlarmManagers 的东西,但不确定如何使用它们来获得我想要的行为,或者这是否是人们使用的东西。

谢谢,如果应用程序处于后台或非活动状态时,是否可以通过 onMessagesRecieved 或任何其他方法自定义有效负载,请告诉我。到目前为止,唯一的其他解决方案是以某种方式将消息的内容发送到服务,但我遇到了这样的问题,即服务无法在后台显示通知而不会导致应用程序崩溃并且不会非常hacky。

【问题讨论】:

    标签: android firebase notifications firebase-cloud-messaging


    【解决方案1】:

    我想出的唯一方法是只发送数据负载,尽管应用程序的状态(前台/后台),它应该被传递到 onMessageReceived 回调。

    然后,您将所有必填字段放入数据负载并从中构建通知。这里的地图“数据”来自 remoteMessage.getData()

    private void sendNotification(Map<String, String> data) {
        String body = Optional.ofNullable(data.get("body")).orElse("");
        if (body.isEmpty()) {
            return;
        }
    
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
        Uri sound = getSoundUri(Optional.ofNullable(data.get("sound")).orElse(""));
        String defaultChannel = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                                    ? NotificationChannel.DEFAULT_CHANNEL_ID
                                    : DEFAULT_CHANNEL_ID;
    
        String channel = Optional.ofNullable(data.get("android_channel_id")).orElse(defaultChannel);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(body)
            .setAutoCancel(true)
            .setWhen(System.currentTimeMillis())
            .setShowWhen(true)
            .setContentIntent(resultPendingIntent);
        if (sound != null)
            notificationBuilder.setSound(sound);
    
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    
        if (notificationManager != null)
            notificationManager.notify(0, notificationBuilder.build());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 2014-10-20
      相关资源
      最近更新 更多