Notifications fail to display in Android Oreo (API 26)

前端 未结 4 838
[愿得一人]
[愿得一人] 2020-11-30 05:32

I get this message when trying to display a notification on Android O.

Use of stream types is deprecated for operations other than volume control

4条回答
  •  时光说笑
    2020-11-30 06:12

    All that @sky-kelsey has described is good, Just minor additions:

    You should not register same channel every time if it has been already registered, so I have Utils class method that creates a channel for me:

    public static final String NOTIFICATION_CHANNEL_ID_LOCATION = "notification_channel_location";
    
    public static void registerLocationNotifChnnl(Context context) {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationManager mngr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            if (mngr.getNotificationChannel(NOTIFICATION_CHANNEL_ID_LOCATION) != null) {
                return;
            }
            //
            NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID_LOCATION,
                    context.getString(R.string.notification_chnnl_location),
                    NotificationManager.IMPORTANCE_LOW);
            // Configure the notification channel.
            channel.setDescription(context.getString(R.string.notification_chnnl_location_descr));
            channel.enableLights(false);
            channel.enableVibration(false);
            mngr.createNotificationChannel(channel);
        }
    }
    

    strings.xml:

    Location polling
    You will see notifications on this channel ONLY during location polling
    

    And I call the method every time before I'm going to show a notification of the type:

        ...
        NotificationUtil.registerLocationNotifChnnl(this);
        return new NotificationCompat.Builder(this, NotificationUtil.NOTIFICATION_CHANNEL_ID_LOCATION)
                .addAction(R.mipmap.ic_launcher, getString(R.string.open_app),
                        activityPendingIntent)
                .addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.remove_location_updates),
                        servicePendingIntent)
                .setContentText(text)
                ...
    

    Another typical problem - channel default sound - described here: https://stackoverflow.com/a/45920861/2133585

提交回复
热议问题