下面列出了怎么用android.app.NotificationChannelGroup的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void createNotificationChannelGroup(String pkg, int uid, NotificationChannelGroup group,
boolean fromTargetApp) {
Preconditions.checkNotNull(pkg);
Preconditions.checkNotNull(group);
Preconditions.checkNotNull(group.getId());
Preconditions.checkNotNull(!TextUtils.isEmpty(group.getName()));
Record r = getOrCreateRecord(pkg, uid);
if (r == null) {
throw new IllegalArgumentException("Invalid package");
}
final NotificationChannelGroup oldGroup = r.groups.get(group.getId());
if (!group.equals(oldGroup)) {
// will log for new entries as well as name/description changes
MetricsLogger.action(getChannelGroupLog(group.getId(), pkg));
}
if (oldGroup != null) {
group.setChannels(oldGroup.getChannels());
if (fromTargetApp) {
group.setBlocked(oldGroup.isBlocked());
}
}
r.groups.put(group.getId(), group);
}
public NotificationChannelGroup getNotificationChannelGroupWithChannels(String pkg,
int uid, String groupId, boolean includeDeleted) {
Preconditions.checkNotNull(pkg);
Record r = getRecord(pkg, uid);
if (r == null || groupId == null || !r.groups.containsKey(groupId)) {
return null;
}
NotificationChannelGroup group = r.groups.get(groupId).clone();
group.setChannels(new ArrayList<>());
int N = r.channels.size();
for (int i = 0; i < N; i++) {
final NotificationChannel nc = r.channels.valueAt(i);
if (includeDeleted || !nc.isDeleted()) {
if (groupId.equals(nc.getGroup())) {
group.addChannel(nc);
}
}
}
return group;
}
/**
* Create push notification channel group.
*
* @param context The application context.
* @param groupId The id of the group.
* @param groupName The user-visible name of the group.
*/
private static void createNotificationGroup(Context context, String groupId, String groupName) {
if (context == null || TextUtils.isEmpty(groupId)) {
return;
}
if (BuildUtil.isNotificationChannelSupported(context)) {
try {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager == null) {
Log.e("Notification manager is null");
return;
}
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup(groupId,
groupName));
} catch (Throwable t) {
Util.handleException(t);
}
}
}
private void createNotifyChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannelGroup(
new NotificationChannelGroup(mGroupId, mGroupName));
NotificationChannel channelMsg =
new NotificationChannel(mChannelMsgId, mChannelMsgName,
NotificationManager.IMPORTANCE_DEFAULT);
channelMsg.setDescription(mChannelMsgDes);
channelMsg.enableLights(true);
channelMsg.setLightColor(Color.BLUE);
channelMsg.enableVibration(false);
channelMsg.setVibrationPattern(new long[] { 100, 200, 300, 400 });
channelMsg.setShowBadge(true);
channelMsg.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channelMsg.setGroup(mGroupId);
mNotificationManager.createNotificationChannel(channelMsg);
NotificationChannel channelService =
new NotificationChannel(mChannelServiceId, mChannelServiceName,
NotificationManager.IMPORTANCE_LOW);
channelService.setDescription(mChannelServiceDes);
channelService.enableLights(false);
channelService.enableVibration(false);
channelService.setShowBadge(false);
channelService.setSound(null, null);
channelService.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channelService.setGroup(mGroupId);
mNotificationManager.createNotificationChannel(channelService);
}
}
}
@TargetApi(26)
private static void onCreate(@NonNull Context context, @NonNull NotificationManager notificationManager) {
NotificationChannelGroup messagesGroup = new NotificationChannelGroup(CATEGORY_MESSAGES, context.getResources().getString(R.string.NotificationChannel_group_messages));
notificationManager.createNotificationChannelGroup(messagesGroup);
NotificationChannel messages = new NotificationChannel(getMessagesChannel(context), context.getString(R.string.NotificationChannel_messages), NotificationManager.IMPORTANCE_HIGH);
NotificationChannel calls = new NotificationChannel(CALLS, context.getString(R.string.NotificationChannel_calls), NotificationManager.IMPORTANCE_HIGH);
NotificationChannel failures = new NotificationChannel(FAILURES, context.getString(R.string.NotificationChannel_failures), NotificationManager.IMPORTANCE_HIGH);
NotificationChannel backups = new NotificationChannel(BACKUPS, context.getString(R.string.NotificationChannel_backups), NotificationManager.IMPORTANCE_LOW);
NotificationChannel lockedStatus = new NotificationChannel(LOCKED_STATUS, context.getString(R.string.NotificationChannel_locked_status), NotificationManager.IMPORTANCE_LOW);
NotificationChannel other = new NotificationChannel(OTHER, context.getString(R.string.NotificationChannel_other), NotificationManager.IMPORTANCE_LOW);
messages.setGroup(CATEGORY_MESSAGES);
messages.enableVibration(TextSecurePreferences.isNotificationVibrateEnabled(context));
messages.setSound(TextSecurePreferences.getNotificationRingtone(context), getRingtoneAudioAttributes());
setLedPreference(messages, TextSecurePreferences.getNotificationLedColor(context));
calls.setShowBadge(false);
backups.setShowBadge(false);
lockedStatus.setShowBadge(false);
other.setShowBadge(false);
notificationManager.createNotificationChannels(Arrays.asList(messages, calls, failures, backups, lockedStatus, other));
if (BuildConfig.AUTOMATIC_UPDATES) {
NotificationChannel appUpdates = new NotificationChannel(APP_UPDATES, context.getString(R.string.NotificationChannel_app_updates), NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(appUpdates);
} else {
notificationManager.deleteNotificationChannel(APP_UPDATES);
}
}
@Override
public boolean isGroupBlocked(String packageName, int uid, String groupId) {
if (groupId == null) {
return false;
}
Record r = getOrCreateRecord(packageName, uid);
NotificationChannelGroup group = r.groups.get(groupId);
if (group == null) {
return false;
}
return group.isBlocked();
}
public NotificationChannelGroup getNotificationChannelGroup(String groupId, String pkg,
int uid) {
Preconditions.checkNotNull(pkg);
Record r = getRecord(pkg, uid);
if (r == null) {
return null;
}
return r.groups.get(groupId);
}
@Override
public Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
int uid) {
Record r = getRecord(pkg, uid);
if (r == null) {
return new ArrayList<>();
}
return r.groups.values();
}
private static void dumpRecords(ProtoOutputStream proto, long fieldId,
@NonNull NotificationManagerService.DumpFilter filter,
ArrayMap<String, Record> records) {
final int N = records.size();
long fToken;
for (int i = 0; i < N; i++) {
final Record r = records.valueAt(i);
if (filter.matches(r.pkg)) {
fToken = proto.start(fieldId);
proto.write(RecordProto.PACKAGE, r.pkg);
proto.write(RecordProto.UID, r.uid);
proto.write(RecordProto.IMPORTANCE, r.importance);
proto.write(RecordProto.PRIORITY, r.priority);
proto.write(RecordProto.VISIBILITY, r.visibility);
proto.write(RecordProto.SHOW_BADGE, r.showBadge);
for (NotificationChannel channel : r.channels.values()) {
channel.writeToProto(proto, RecordProto.CHANNELS);
}
for (NotificationChannelGroup group : r.groups.values()) {
group.writeToProto(proto, RecordProto.CHANNEL_GROUPS);
}
proto.end(fToken);
}
}
}
/**
* Returns all notification channel groups belonging to the given package for a given user.
*
* <p>This method will throw a security exception if you don't have access to notifications
* for the given user.</p>
* <p>The caller must have {@link CompanionDeviceManager#getAssociations() an associated
* device} in order to use this method.
*
* @param pkg The package to retrieve channel groups for.
*/
public final List<NotificationChannelGroup> getNotificationChannelGroups(@NonNull String pkg,
@NonNull UserHandle user) {
if (!isBound()) return null;
try {
return getNotificationInterface().getNotificationChannelGroupsFromPrivilegedListener(
mWrapper, pkg, user).getList();
} catch (RemoteException e) {
Log.v(TAG, "Unable to contact notification manager", e);
throw e.rethrowFromSystemServer();
}
}
@Override
public void onNotificationChannelGroupModification(String pkgName, UserHandle user,
NotificationChannelGroup group,
@ChannelOrGroupModificationTypes int modificationType) {
SomeArgs args = SomeArgs.obtain();
args.arg1 = pkgName;
args.arg2 = user;
args.arg3 = group;
args.arg4 = modificationType;
mHandler.obtainMessage(
MyHandler.MSG_ON_NOTIFICATION_CHANNEL_GROUP_MODIFIED, args).sendToTarget();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private static List<NotificationChannelGroupCompat> convertGroupListToCompat(List<NotificationChannelGroup> originals) {
List<NotificationChannelGroupCompat> channels = new ArrayList<>(originals.size());
for (NotificationChannelGroup origin : originals)
channels.add(new NotificationChannelGroupCompat(origin));
return channels;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private static List<NotificationChannelGroup> convertGroupCompatToList(List<NotificationChannelGroupCompat> originals) {
List<NotificationChannelGroup> channels = new ArrayList<>(originals.size());
for (NotificationChannelGroupCompat origin : originals)
channels.add(origin.getOreoVersion());
return channels;
}
@RequiresApi(api = Build.VERSION_CODES.O)
void createNotificationChannel(Context context) {
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannelGroup group = new NotificationChannelGroup("group." + id, name);
nm.createNotificationChannelGroup(group);
NotificationChannel channel = new NotificationChannel(
getNotificationChannelId(id), name,
NotificationManager.IMPORTANCE_HIGH);
channel.setGroup(group.getId());
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.enableLights(true);
nm.createNotificationChannel(channel);
}
@RequiresApi(api = Build.VERSION_CODES.O)
void createNotificationChannel(Context context) {
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannelGroup group = new NotificationChannelGroup("group." + accountId, accountName);
nm.createNotificationChannelGroup(group);
NotificationChannel channel = new NotificationChannel(
getNotificationChannelId(id), getDisplayName(context),
NotificationManager.IMPORTANCE_HIGH);
channel.setGroup(group.getId());
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.enableLights(true);
nm.createNotificationChannel(channel);
}
/**
* Get list of Notification groups.
*
* @param context The application context.
* @return Returns all notification groups.
*/
static List<NotificationChannelGroup> getNotificationGroups(Context context) {
if (BuildUtil.isNotificationChannelSupported(context)) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
if (notificationManager == null) {
Log.e("Cannot get Notification Channel Groups, notificationManager is null.");
return null;
}
return notificationManager.getNotificationChannelGroups();
}
return null;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void notificationGroupInit(int group_id, int group_name) {
// 通知渠道组的id.
String group = getString(group_id);
// 用户可见的通知渠道组名称.
CharSequence name = getString(group_name);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(group, name));
}
private static void createChannelGroup(Context ctx, String id, CharSequence name) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
return;
NotificationChannelGroup group = new NotificationChannelGroup(id, name);
android.app.NotificationManager mgr = (android.app.NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mgr.createNotificationChannelGroup(group);
}
public static NotificationChannel registerChannelIfNeeded(Context context, String packageName) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return null;
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = getChannelIdByPkg(packageName);
NotificationChannel notificationChannel = manager.getNotificationChannel(channelId);
if (notificationChannel != null) {
if (ID_GROUP_APPLICATIONS.equals(notificationChannel.getGroup()) || TextUtils.isEmpty(notificationChannel.getGroup())) {
manager.deleteNotificationChannel(channelId);
notificationChannel = null;
}
}
if (notificationChannel == null) {
CharSequence name = ApplicationNameCache.getInstance().getAppName(context, packageName);
if (name == null) {
return null;
}
NotificationChannelGroup notificationChannelGroup = createGroupWithPackage(packageName, name);
manager.createNotificationChannelGroup(notificationChannelGroup);
notificationChannel = createChannelWithPackage(packageName, name);
notificationChannel.setGroup(notificationChannelGroup.getId());
manager.createNotificationChannel(notificationChannel);
}
return notificationChannel;
}
@TargetApi(26)
public static void cleanAllNotificationChannels() {
// TODO this isn't right yet
List<NotificationChannel> channels = getNotifManager().getNotificationChannels();
for (NotificationChannel channel : channels) {
getNotifManager().deleteNotificationChannel(channel.getId());
}
List<NotificationChannelGroup> groups = getNotifManager().getNotificationChannelGroups();
for (NotificationChannelGroup group : groups) {
getNotifManager().deleteNotificationChannel(group.getId());
}
}
@TargetApi(26)
public static void cleanAllNotificationChannels() {
// TODO this isn't right yet
List<NotificationChannel> channels = getNotifManager().getNotificationChannels();
for (NotificationChannel channel : channels) {
getNotifManager().deleteNotificationChannel(channel.getId());
}
List<NotificationChannelGroup> groups = getNotifManager().getNotificationChannelGroups();
for (NotificationChannelGroup group : groups) {
getNotifManager().deleteNotificationChannel(group.getId());
}
}
private String getNotificationChannelGroup(NotificationManagerCompat notificationManager) {
if (notificationChannelsSupported() && notificationManager.getNotificationChannelGroup(CH_GRP_MSG) == null) {
NotificationChannelGroup chGrp = new NotificationChannelGroup(CH_GRP_MSG, context.getString(R.string.pref_chats));
notificationManager.createNotificationChannelGroup(chGrp);
}
return CH_GRP_MSG;
}
public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
out.startTag(null, TAG_RANKING);
out.attribute(null, ATT_VERSION, Integer.toString(XML_VERSION));
synchronized (mRecords) {
final int N = mRecords.size();
for (int i = 0; i < N; i++) {
final Record r = mRecords.valueAt(i);
//TODO: http://b/22388012
if (forBackup && UserHandle.getUserId(r.uid) != UserHandle.USER_SYSTEM) {
continue;
}
final boolean hasNonDefaultSettings =
r.importance != DEFAULT_IMPORTANCE
|| r.priority != DEFAULT_PRIORITY
|| r.visibility != DEFAULT_VISIBILITY
|| r.showBadge != DEFAULT_SHOW_BADGE
|| r.lockedAppFields != DEFAULT_LOCKED_APP_FIELDS
|| r.channels.size() > 0
|| r.groups.size() > 0;
if (hasNonDefaultSettings) {
out.startTag(null, TAG_PACKAGE);
out.attribute(null, ATT_NAME, r.pkg);
if (r.importance != DEFAULT_IMPORTANCE) {
out.attribute(null, ATT_IMPORTANCE, Integer.toString(r.importance));
}
if (r.priority != DEFAULT_PRIORITY) {
out.attribute(null, ATT_PRIORITY, Integer.toString(r.priority));
}
if (r.visibility != DEFAULT_VISIBILITY) {
out.attribute(null, ATT_VISIBILITY, Integer.toString(r.visibility));
}
out.attribute(null, ATT_SHOW_BADGE, Boolean.toString(r.showBadge));
out.attribute(null, ATT_APP_USER_LOCKED_FIELDS,
Integer.toString(r.lockedAppFields));
if (!forBackup) {
out.attribute(null, ATT_UID, Integer.toString(r.uid));
}
for (NotificationChannelGroup group : r.groups.values()) {
group.writeXml(out);
}
for (NotificationChannel channel : r.channels.values()) {
if (forBackup) {
if (!channel.isDeleted()) {
channel.writeXmlForBackup(out, mContext);
}
} else {
channel.writeXml(out);
}
}
out.endTag(null, TAG_PACKAGE);
}
}
}
out.endTag(null, TAG_RANKING);
}
@Override
public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
int uid, boolean includeDeleted, boolean includeNonGrouped, boolean includeEmpty) {
Preconditions.checkNotNull(pkg);
Map<String, NotificationChannelGroup> groups = new ArrayMap<>();
Record r = getRecord(pkg, uid);
if (r == null) {
return ParceledListSlice.emptyList();
}
NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
int N = r.channels.size();
for (int i = 0; i < N; i++) {
final NotificationChannel nc = r.channels.valueAt(i);
if (includeDeleted || !nc.isDeleted()) {
if (nc.getGroup() != null) {
if (r.groups.get(nc.getGroup()) != null) {
NotificationChannelGroup ncg = groups.get(nc.getGroup());
if (ncg == null) {
ncg = r.groups.get(nc.getGroup()).clone();
ncg.setChannels(new ArrayList<>());
groups.put(nc.getGroup(), ncg);
}
ncg.addChannel(nc);
}
} else {
nonGrouped.addChannel(nc);
}
}
}
if (includeNonGrouped && nonGrouped.getChannels().size() > 0) {
groups.put(null, nonGrouped);
}
if (includeEmpty) {
for (NotificationChannelGroup group : r.groups.values()) {
if (!groups.containsKey(group.getId())) {
groups.put(group.getId(), group);
}
}
}
return new ParceledListSlice<>(new ArrayList<>(groups.values()));
}
private static void dumpRecords(PrintWriter pw, String prefix,
@NonNull NotificationManagerService.DumpFilter filter,
ArrayMap<String, Record> records) {
final int N = records.size();
for (int i = 0; i < N; i++) {
final Record r = records.valueAt(i);
if (filter.matches(r.pkg)) {
pw.print(prefix);
pw.print(" AppSettings: ");
pw.print(r.pkg);
pw.print(" (");
pw.print(r.uid == Record.UNKNOWN_UID ? "UNKNOWN_UID" : Integer.toString(r.uid));
pw.print(')');
if (r.importance != DEFAULT_IMPORTANCE) {
pw.print(" importance=");
pw.print(Ranking.importanceToString(r.importance));
}
if (r.priority != DEFAULT_PRIORITY) {
pw.print(" priority=");
pw.print(Notification.priorityToString(r.priority));
}
if (r.visibility != DEFAULT_VISIBILITY) {
pw.print(" visibility=");
pw.print(Notification.visibilityToString(r.visibility));
}
pw.print(" showBadge=");
pw.print(Boolean.toString(r.showBadge));
pw.println();
for (NotificationChannel channel : r.channels.values()) {
pw.print(prefix);
pw.print(" ");
pw.print(" ");
pw.println(channel);
}
for (NotificationChannelGroup group : r.groups.values()) {
pw.print(prefix);
pw.print(" ");
pw.print(" ");
pw.println(group);
}
}
}
}
Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
int uid);
void createNotificationChannelGroup(String pkg, int uid, NotificationChannelGroup group,
boolean fromTargetApp);
ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
int uid, boolean includeDeleted, boolean includeNonGrouped, boolean includeEmpty);
@RequiresApi(api = Build.VERSION_CODES.O)
protected NotificationChannelGroupCompat(NotificationChannelGroup original) {
_notificationChannelGroup = original;
this.mId = _notificationChannelGroup.getId(); // just to make compiler happy
}
@RequiresApi(api = Build.VERSION_CODES.O)
NotificationChannelGroup getOreoVersion() {
return _notificationChannelGroup;
}