首页 > 解决方案 > Android notification's names on settings like facebook

问题描述

I would like to make users able to disable/enable notifications separately by their functionalities from settings app like Facebook or other applications do.

As image, Facebook shows a title for each notification use case (as you can understand from my terrible English I'm Italian, so screenshot is in Italian too), so users can disable or enable notifications depending on his need.

How can I do it? Can you post me a code example? Thank you very much and tell me if I wasn't clear

enter image description here

标签: androidpush-notificationnotificationsapplication-settings

解决方案


您需要创建通知渠道。这是我为此目的创建的 Util 方法:

public void createChannel(String channelId, CharSequence channelName, int importance) {
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    channel = new NotificationChannel(channelId, channelName, importance);
    channel.enableLights(true);
    channel.setLightColor(Color.RED);
    channel.enableVibration(true);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    notificationManager.createNotificationChannel(channel);
}

哪里channelnotificationManager

private NotificationChannel channel;
private NotificationManager notificationManager;

只需使用 命名频道channelId并使用channelName

这是 Javadoc 的NotificationChannel

/**
     * Creates a notification channel.
     *
     * @param id The id of the channel. Must be unique per package. The value may be truncated if
     *           it is too long.
     * @param name The user visible name of the channel. You can rename this channel when the system
     *             locale changes by listening for the {@link Intent#ACTION_LOCALE_CHANGED}
     *             broadcast. The recommended maximum length is 40 characters; the value may be
     *             truncated if it is too long.
     * @param importance The importance of the channel. This controls how interruptive notifications
     *                   posted to this channel are.
     */
    public NotificationChannel(String id, CharSequence name, @Importance int importance) {
        this.mId = getTrimmedString(id);
        this.mName = name != null ? getTrimmedString(name.toString()) : null;
        this.mImportance = importance;
    }

推荐阅读