这是通过将通知优先级设置为最小来完成的。
例如:
NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MyReminder");
b.setPriority(NotificationCompat.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String id = MyApp.getNotificationChannel(context);
b.setChannelId(id);
}
注意:对于oreo和更高版本,您还需要设置通知通道的优先级:
final private static String MyChannelID = "MyChannel_1";
private static NotificationChannel channel;
static private String getNotificationChannel(Context context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (channel == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "My Reminders";
String description = "My Reminders pre-scheduled using My app";
int importance = NotificationManager.IMPORTANCE_MIN;
channel = new NotificationChannel(MyChannelID, name, importance);
channel.setDescription(description);
channel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
channel.setLightColor(Color.RED);
channel.enableVibration(true);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
getNotificationManager().createNotificationChannel(channel);
}
}
return MyChannelID;
}
static public NotificationManager getNotificationManager() {
Context context = App.getContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return context.getSystemService(NotificationManager.class);
}
else {
return (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
}
}
我没有检查每个优先级的行为,而是检查最小值和重要值。如果您有更具体的行为,您可以查看文档并使用其他优先级。