下面列出了怎么用android.app.NotificationChannel的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a notification that shows, that we got a keep alive timeout
*/
@SuppressLint("InlinedApi")
private void showKeepAliveDisconnectNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
App.notificationChannel, "Default",
NotificationManager.IMPORTANCE_LOW
);
mNotificationManager.createNotificationChannel(notificationChannel);
}
Notification notification = new NotificationCompat.Builder(this, App.notificationChannel)
.setSmallIcon(R.drawable.notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notification_disconnect_keep_alive))
.setAutoCancel(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(Utilities.getClementineRemotePendingIntent(this))
.build();
mNotificationManager
.notify(ClementineMediaSessionNotification.NOTIFIFCATION_ID, notification);
}
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel() {
if (mNotificationManager.getNotificationChannel(CHANNEL_ID) == null) {
// The user-visible name of the channel.
CharSequence name = "MediaSession";
// The user-visible description of the channel.
String description = "MediaSession and MediaPlayer";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(
new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
Log.d(TAG, "createChannel: New channel created");
} else {
Log.d(TAG, "createChannel: Existing channel reused");
}
}
@TargetApi(26)
private static @NonNull NotificationChannel copyChannel(@NonNull NotificationChannel original, @NonNull String id) {
NotificationChannel copy = new NotificationChannel(id, original.getName(), original.getImportance());
copy.setGroup(original.getGroup());
copy.setSound(original.getSound(), original.getAudioAttributes());
copy.setBypassDnd(original.canBypassDnd());
copy.enableVibration(original.shouldVibrate());
copy.setVibrationPattern(original.getVibrationPattern());
copy.setLockscreenVisibility(original.getLockscreenVisibility());
copy.setShowBadge(original.canShowBadge());
copy.setLightColor(original.getLightColor());
copy.enableLights(original.shouldShowLights());
return copy;
}
private void triggerNotification(String title, String content) {
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(rv_channel, "ReservedValuesSync", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(getApplicationContext(), rv_channel)
.setSmallIcon(R.drawable.ic_sync)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
notificationManager.notify(ReservedValuesWorker.SYNC_RV_ID, notificationBuilder.build());
}
@TargetApi(26)
public static boolean isSoundDifferent(String id, NotificationChannel x) {
if (x.getSound() == null) return false; // this does not have a sound
final NotificationChannel c = getNotifManager().getNotificationChannel(id);
if (c == null) return false; // no channel with this id
if (c.getSound() == null)
return false; // this maybe will only happen if user disables sound so lets not create a new one in that case
final String original_sound = PersistentStore.getString("original-channel-sound-" + id);
if (original_sound.equals("")) {
PersistentStore.setString("original-channel-sound-" + id, x.getSound().toString());
return false; // no existing record so save the original and do nothing else
}
if (original_sound.equals(x.getSound().toString()))
return false; // its the same sound still
return true; // the sound has changed vs the original
}
private void createNotificationChannel()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
AudioAttributes attr = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
CharSequence name = context.getString(R.string.app_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.setSound(notification, attr);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
public static void createNotificationChannels(Context appCtx) {
try {
final NotificationManager notificationManager = (NotificationManager) appCtx.getSystemService(Context.NOTIFICATION_SERVICE);
// Notification with sound channel
CharSequence name = appCtx.getString(R.string.export_notification);
String description = appCtx.getString(R.string.export_notification_description);
NotificationChannel channel = new NotificationChannel("export_sound", name, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(description);
channel.enableVibration(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(channel);
} catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onCreate() {
super.onCreate();
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) || new AppPreferences(getApplicationContext()).getBoolean("useForegroundService", false)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder mBuilder = new Notification.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setContentText(getString(R.string.backgroundService));
NotificationChannel channel = new NotificationChannel("BackgroundService", getString(R.string.backgroundService), NotificationManager.IMPORTANCE_NONE);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("BackgroundService");
Intent resultIntent = new Intent(getApplicationContext(), Main.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
startForeground(1, mBuilder.build());
} else {
startForeground(1, new Notification());
}
}
}
/**
* for API 26+ create notification channels
*/
private void createchannel() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = new NotificationChannel(id,
getString(R.string.channel_name), //name of the channel
NotificationManager.IMPORTANCE_DEFAULT); //importance level
//important level: default is is high on the phone. high is urgent on the phone. low is medium, so none is low?
// Configure the notification channel.
mChannel.setDescription(getString(R.string.channel_description));
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setShowBadge(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
nm.createNotificationChannel(mChannel);
}
}
private void initNotificationBuilder() {
String channelId = "net_speed";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "NetSpeed", NotificationManager.IMPORTANCE_DEFAULT);
nm.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(service, channelId)
.setWhen(0)
.setColor(ContextCompat.getColor(service, R.color.material_accent_500))
.setTicker(service.getString(R.string.forward_success))
.setContentTitle(profileName)
.setContentIntent(PendingIntent.getActivity(service, 0, new Intent(service, Shadowsocks.class)
.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 0))
.setSmallIcon(R.drawable.ic_stat_shadowsocks);
builder.addAction(R.drawable.ic_navigation_close,
service.getString(R.string.stop),
PendingIntent.getBroadcast(service, 0, new Intent(Constants.Action.CLOSE), 0));
List<Profile> profiles = app.profileManager.getAllProfiles();
if (profiles != null && !profiles.isEmpty()) {
builder.addAction(R.drawable.ic_action_settings, service.getString(R.string.quick_switch),
PendingIntent.getActivity(service, 0, new Intent(Constants.Action.QUICK_SWITCH), 0));
}
}
/**
* Registers notification channels, which can be used later by individual notifications.
*
* @param ctx The application context
*/
public NotificationHelper(Context ctx) {
super(ctx);
NotificationChannel chan1 = new NotificationChannel(PRIMARY_CHANNEL,
getString(R.string.noti_channel_default), NotificationManager.IMPORTANCE_DEFAULT);
chan1.setLightColor(Color.GREEN);
chan1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(chan1);
NotificationChannel chan2 = new NotificationChannel(SECONDARY_CHANNEL,
getString(R.string.noti_channel_second), NotificationManager.IMPORTANCE_HIGH);
chan2.setLightColor(Color.BLUE);
chan2.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(chan2);
}
@TargetApi(Build.VERSION_CODES.O)
private void createNotificationChannels() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel foreground = new NotificationChannel("foreground", getString(R.string.channel_foreground), NotificationManager.IMPORTANCE_MIN);
foreground.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
nm.createNotificationChannel(foreground);
NotificationChannel notify = new NotificationChannel("notify", getString(R.string.channel_notify), NotificationManager.IMPORTANCE_DEFAULT);
notify.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
nm.createNotificationChannel(notify);
NotificationChannel access = new NotificationChannel("access", getString(R.string.channel_access), NotificationManager.IMPORTANCE_DEFAULT);
access.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
nm.createNotificationChannel(access);
}
@Override
protected void onPause() {
unbindService(mSC);
if (mService != null) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("de.vier_bier.habpanelviewer.status", "Status", NotificationManager.IMPORTANCE_MIN);
channel.enableLights(false);
channel.setSound(null, null);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "de.vier_bier.habpanelviewer.status");
builder.setSmallIcon(R.drawable.logo);
mService.startForeground(42, builder.build());
}
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
boolean pauseWebview = prefs.getBoolean(Constants.PREF_PAUSE_WEBVIEW, false);
if (pauseWebview && !((PowerManager) getSystemService(POWER_SERVICE)).isInteractive()) {
mWebView.pause();
}
super.onPause();
}
@Override
public void onCreate() {
super.onCreate();
mBroadcastManager = LocalBroadcastManager.getInstance(this);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mCameraAPI = ((TimelapseApplication) getApplication()).getCameraAPI();
mTimelapseData = ((TimelapseApplication) getApplication()).getTimelapseData();
mApiRequestsList = mTimelapseData.getApiRequestsList();
mStateMachineConnection = ((TimelapseApplication) getApplication()).
getStateMachineConnection();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_MIN;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(false);
mChannel.enableVibration(false);
mNotificationManager.createNotificationChannel(mChannel);
}
}
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel()
{
NotificationManager mNotificationManager = (NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
// The user-visible name of the channel.
CharSequence name = "Media playback";
// The user-visible description of the channel.
String description = "Media playback controls";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.setShowBadge(false);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mNotificationManager.createNotificationChannel(mChannel);
}
@TargetApi(26)
public static boolean isSoundDifferent(String id, NotificationChannel x) {
if (x.getSound() == null) return false; // this does not have a sound
final NotificationChannel c = getNotifManager().getNotificationChannel(id);
if (c == null) return false; // no channel with this id
if (c.getSound() == null)
return false; // this maybe will only happen if user disables sound so lets not create a new one in that case
final String original_sound = PersistentStore.getString("original-channel-sound-" + id);
if (original_sound.equals("")) {
PersistentStore.setString("original-channel-sound-" + id, x.getSound().toString());
return false; // no existing record so save the original and do nothing else
}
if (original_sound.equals(x.getSound().toString()))
return false; // its the same sound still
return true; // the sound has changed vs the original
}
@TargetApi(Build.VERSION_CODES.O)
private void buildNotificationChannel() {
NotificationChannel channel =
new NotificationChannel(NOTIFICATION_CHANNEL,
service.getString(R.string.app_name),
NotificationManager.IMPORTANCE_LOW);
channel.enableLights(false);
channel.enableVibration(false);
channel.setShowBadge(false);
NotificationManager notificationManager =
(NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
}
@VisibleForTesting
void lockFieldsForUpdate(NotificationChannel original, NotificationChannel update) {
if (original.canBypassDnd() != update.canBypassDnd()) {
update.lockFields(NotificationChannel.USER_LOCKED_PRIORITY);
}
if (original.getLockscreenVisibility() != update.getLockscreenVisibility()) {
update.lockFields(NotificationChannel.USER_LOCKED_VISIBILITY);
}
if (original.getImportance() != update.getImportance()) {
update.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
}
if (original.shouldShowLights() != update.shouldShowLights()
|| original.getLightColor() != update.getLightColor()) {
update.lockFields(NotificationChannel.USER_LOCKED_LIGHTS);
}
if (!Objects.equals(original.getSound(), update.getSound())) {
update.lockFields(NotificationChannel.USER_LOCKED_SOUND);
}
if (!Arrays.equals(original.getVibrationPattern(), update.getVibrationPattern())
|| original.shouldVibrate() != update.shouldVibrate()) {
update.lockFields(NotificationChannel.USER_LOCKED_VIBRATION);
}
if (original.canShowBadge() != update.canShowBadge()) {
update.lockFields(NotificationChannel.USER_LOCKED_SHOW_BADGE);
}
}
private Notification createNotification() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
Intent intent = new Intent(this, IdenticonsSettings.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
return new NotificationCompat.Builder(this, TAG)
.setAutoCancel(false)
.setOngoing(true)
.setContentTitle(getString(R.string.identicons_remove_service_running_title))
.setContentText(getString(R.string.identicons_remove_service_running_summary))
.setSmallIcon(R.drawable.ic_settings_identicons)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
}
/**
* Init notification channels for android 8.0 and higher
*/
private String createNotificationChannel(Context context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setDescription(CHANNEL_DESCRIPTION);
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
return CHANNEL_ID;
}
public void initChannels(Context context) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Natrium transaction alerts");
notificationManager.createNotificationChannel(channel);
}
private static void createNotificationChannel(Context c, @NonNull NotificationManager manager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID_NOTIFICATION,
getNotificationChannelName(c, CHANNEL_ID_NOTIFICATION),
NotificationManager.IMPORTANCE_LOW);
channel.setShowBadge(true);
channel.setSound(null, null);
channel.setLightColor(ContextCompat.getColor(c, R.color.colorPrimary_dark));
manager.createNotificationChannel(channel);
}
}
public static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if (notificationManager != null) {
NotificationChannel channel
= new NotificationChannel(context.getPackageName(), context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
}
}
ShowNotification() {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = G.context.getString(R.string.channel_name_notification);// The user-visible name of the channel.
@SuppressLint("WrongConstant") NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
}
private void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
NAVIGATION_NOTIFICATION_CHANNEL, context.getString(R.string.channel_name),
NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(notificationChannel);
}
}
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "应用更新", NotificationManager.IMPORTANCE_LOW);
mChannel.setDescription("应用有新版本");
mChannel.enableLights(true); //是否在桌面icon右上角展示小红点
getManager().createNotificationChannel(mChannel);
}
}
public DownloadApkTask(Context context, DownloadRequest request, Uri uri, String failedUrl) {
mContext = context;
mRequest = request;
mFailedUrl = failedUrl;
mListener = new DownloadApkListener();
mRequest.setListener(mListener);
mNotifyManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = context.getPackageName()+".UPDATE";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotifyManager.createNotificationChannel(
new NotificationChannel(
channelId,
context.getString(R.string.download_update),
NotificationManager.IMPORTANCE_LOW));
}
mDownloadingBuilder = new NotificationCompat.Builder(context, channelId);
mDownloadingBuilder.setContentTitle(context.getString(R.string.downloading_update))
.setSmallIcon(android.R.drawable.stat_sys_download)
.setOngoing(true)
.setAutoCancel(false)
.setProgress(0, 0, true)
.setChannelId(channelId);
mNotifyManager.notify(NOTIFY_ID_DOWNLOADING, mDownloadingBuilder.build());
mDownloadTimer = new DownloadTimer(2000);
mDownloadTimer.start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// Only use content uri for Android N and above
mUri = UpdateApkProvider.UPDATE_APK_URI;
UpdateApkProvider.setUpdateApkFile(uri);
} else {
mUri = uri;
}
}
@TargetApi(26)
private static void setLedPreference(@NonNull NotificationChannel channel, @NonNull String ledColor) {
if ("none".equals(ledColor)) {
channel.enableLights(false);
} else {
channel.enableLights(true);
channel.setLightColor(Color.parseColor(ledColor));
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private static void createNotificationChannel(Context context) {
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = new NotificationChannel(
context.getString(R.string.file_op_channel_id),
context.getString(R.string.file_op_channel_name),
NotificationManager.IMPORTANCE_LOW);
mChannel.setDescription(context.getString(R.string.file_op_channel_description));
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel for the "current activity"
CharSequence name = ActivityDiaryApplication.getAppContext().getResources().getString(R.string.notif_channel_current_activity_name);
String description = ActivityDiaryApplication.getAppContext().getResources().getString(R.string.notif_channel_current_activity_desc);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel nChannel = new NotificationChannel(CURRENT_ACTIVITY_CHANNEL_ID, name, importance);
nChannel.setDescription(description);
NotificationManager notificationManager = (NotificationManager) ActivityDiaryApplication.getAppContext().getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(nChannel);
}
}