FCM を Firebase コンソールから使う

以前まとめておいたつもりが時間が経つとすぐに理解できない。

FCM と Notification の併用をやめてバックグラウンド受信時にうれしがる

もう、面倒くさいので忘れていても直感的すぐに使いたいので

WEBで提供されている Firebaseコンソール(コンポーザー?)から。

 

送信時の「メッセージ」は必須である

APIから送信する場合は、「データ」のみでバックグランドでしれっと端末に渡すことができるが、

WEB画面から送信する場合は「メッセージ」の入力なしでは送信ボタンがが有効化されず送信できない。

 

送信時にアプリがフォアグラウンドの場合

通知バーは表示されない。

「データ」は、端末内で稼働している Service で受け取る。

「データ」がなければ何も起きない。

 

アプリがバックグラウンドの場合

「メッセージ」と「データ」は通知バーに入る。

「データ」のタイトルは通知バーに表示され、キーと値のペアデータは PendingIntent として通知バーに入る。

 

どう使う?

端末内でプロセスが死んでない限りはフォア/バックグラウンド共に同じ挙動としたい。

フォアグラウンド受信時にも同じ挙動をするように、サービスに処理を追加。

QucikStart のサンプル内に未稼働のコードがある。


/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent 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);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

quickstart-android/MyFirebaseMessagingService.java at master · firebase/quickstart-android

結局は、起動されるActivityでIntentを受けるような処理を記述しなければならない。 これ書くと見通し悪くなる。きもい。


if (getIntent().getExtras() != null) {
    for (String key : getIntent().getExtras().keySet()) {
        Object value = getIntent().getExtras().get(key);
        Log.d(TAG, "Key: " + key + " Value: " + value);
    }
}

quickstart-android/MainActivity.java at master · firebase/quickstart-android

直感的にそのまま使うと、単に「アプリ起動を喚起するだけのもの」になってしまいがちだのだが、きもい。