Android FCM failed to post notification on channel “my_channel_01”

前端 未结 1 1236
暗喜
暗喜 2021-01-14 06:23

I am sending push notification message from Firebase console to my app running on emulator.

The MyFirebaseMessagingService class looks like this:

相关标签:
1条回答
  • 2021-01-14 06:27

    When your build specifies a targetSdkVersion of 26, and you run on an API level 26 device or emulator, you must both specify a channel ID when constructing NotificationCompat.Builder, and also create the channel.

    You could use a method like this:

    public static final String NOTIF_CHANNEL_ID = "my_channel_01";
    
    ...
    
    @RequiresApi(Build.VERSION_CODES.O)
    private void createNotifChannel(Context context) {
        NotificationChannel channel = new NotificationChannel(NOTIF_CHANNEL_ID,
                "MyApp events", NotificationManager.IMPORTANCE_LOW);
        // Configure the notification channel
        channel.setDescription("MyApp event controls");
        channel.setShowBadge(false);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    
        NotificationManager manager = context.getSystemService(NotificationManager.class);
    
        manager.createNotificationChannel(channel);
        Log.d(TAG, "createNotifChannel: created=" + NOTIF_CHANNEL_ID);
    }
    

    And because it is only needed for API 26 and requires that level, invoke it like this:

    // The channel need only be created for API 26 devices.  For devices
    // running an API less the 26, there is no way to create a channel and the
    // channel ID specified in the constuctor to NotificationCompat.Builder is
    // merely a placeholder.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotifChannel(this);
    }
    

    It does no harm to recreate the NotificationChannel, which provides some flexibility in where you do it. If your app has multiple entry points (activity, broadcast receiver, etc) take care to ensure the channel is created for all cases. You can also ensure it is only created once using NotificationManager.getNotificationChannel():

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (manager.getNotificationChannel(NOTIF_CHANNEL_ID) == null) {
            createNotifChannel(this);
        }
    }
    
    0 讨论(0)
提交回复
热议问题