下面列出了android.app.NotificationManager#createNotificationChannel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequiresApi(Build.VERSION_CODES.O)
private void createChannelIdWeb() {
//用唯一的ID创建渠道对象
NotificationChannel firstChannel = new NotificationChannel(channelIdWeb,
getString(R.string.web_menu),
NotificationManager.IMPORTANCE_LOW);
//初始化channel
firstChannel.enableLights(false);
firstChannel.enableVibration(false);
firstChannel.setSound(null, null);
//向notification manager 提交channel
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(firstChannel);
}
}
public static void 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) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(BEDTIME_CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.setBypassDnd(true);
channel.enableLights(true);
//channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
// 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);
}
}
/**
* Post a notification to be shown in the status bar.
*
* @param tag A string identifier for this notification. May be {@code null}.
* @param id An identifier for this notification.
* @param channelConfig The notification channel of config.
* @param consumer The consumer of create the builder of notification.
*/
public static void notify(String tag, int id, ChannelConfig channelConfig, Utils.Consumer<NotificationCompat.Builder> consumer) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) Utils.getApp().getSystemService(Context.NOTIFICATION_SERVICE);
//noinspection ConstantConditions
nm.createNotificationChannel(channelConfig.getNotificationChannel());
}
NotificationManagerCompat nmc = NotificationManagerCompat.from(Utils.getApp());
NotificationCompat.Builder builder = new NotificationCompat.Builder(Utils.getApp());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(channelConfig.mNotificationChannel.getId());
}
consumer.accept(builder);
nmc.notify(tag, id, builder.build());
}
@Override
public void onCreate() {
super.onCreate();
ApplicationLoader.postInitApplication();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "push_service_channel";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"Push Notifications Service",NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
Intent explainIntent = new Intent("android.intent.action.VIEW");
explainIntent.setData(Uri.parse("https://github.com/Telegram-FOSS-Team/Telegram-FOSS/blob/master/Notifications.md"));
PendingIntent explainPendingIntent = PendingIntent.getActivity(this, 0, explainIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentIntent(explainPendingIntent)
.setShowWhen(false)
.setOngoing(true)
.setSmallIcon(R.drawable.notification)
.setContentText("Push service: tap to learn more").build();
startForeground(9999,notification);
}
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
getString(R.string.apply_on_boot), NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
Notification.Builder builder = new Notification.Builder(
this, CHANNEL_ID);
builder.setContentTitle(getString(R.string.apply_on_boot))
.setSmallIcon(R.mipmap.ic_launcher);
startForeground(NotificationId.APPLY_ON_BOOT, builder.build());
}
}
public static synchronized String getFileOperationsNotificationsChannelId(Context context)
{
if (fileOperationsNotificationsChannelId == null)
{
fileOperationsNotificationsChannelId = "com.sovworks.eds.FILE_OPERATIONS_CHANNEL2";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
fileOperationsNotificationsChannelId,
context.getString(R.string.file_operations_notifications_channel_name),
NotificationManager.IMPORTANCE_LOW
);
channel.enableLights(false);
channel.enableVibration(false);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
return fileOperationsNotificationsChannelId;
}
private void initNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//创建通知渠道
CharSequence name = "运行通知";
String description = "服务运行中";
String channelId=UNLOCK_NOTIFICATION_CHANNEL_ID;//渠道id
int importance = NotificationManager.IMPORTANCE_DEFAULT;//重要性级别
NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
mChannel.setDescription(description);//渠道描述
mChannel.enableLights(false);//是否显示通知指示灯
mChannel.enableVibration(false);//是否振动
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(mChannel);//创建通知渠道
}
}
@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel()
{
String channelId = NOTIFICATION_CHANNEL_ID;
String channelName = getString(R.string.notificationChannelName);
NotificationChannel chan = new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_LOW);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if(service != null)
{
service.createNotificationChannel(chan);
}
else
{
Log.w(TAG, "Could not get NotificationManager");
}
return channelId;
}
/**
* Set default channel for Android Oreo or newer version
* Notice: it isn"t necessary to invoke this method for any Android version before Oreo.
*
* @param context context
* @param channelId default channel id.
*/
@TargetApi(Build.VERSION_CODES.O)
public static void setDefaultChannelId(Context context, String channelId) {
DefaultChannelId = channelId;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
// do nothing for Android versions before Ore
return;
}
try {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getPackageName();
String description = "PushNotification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
android.app.NotificationChannel channel = new android.app.NotificationChannel(channelId, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
} catch (Exception ex) {
LOGGER.w("failed to create NotificationChannel, then perhaps PushNotification doesn't work well on Android O and newer version.");
}
}
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;
}
private void initNotificationChannels() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || notificationManager == null) {
return;
}
notificationManager.createNotificationChannel(
new NotificationChannel(getString(R.string.live_streamer_notification_id), "New Streamer is live", NotificationManager.IMPORTANCE_LOW)
);
notificationManager.createNotificationChannel(
new NotificationChannel(getString(R.string.stream_cast_notification_id), "Stream Playback Control", NotificationManager.IMPORTANCE_DEFAULT)
);
}
public DownProgressNotify(){
//this.context=context;
notificationManager = (NotificationManager) x.app().getSystemService(x.app().NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(x.app().getPackageName(), x.app().getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
channel.enableLights(false);
channel.enableVibration(false);
notificationManager.createNotificationChannel(channel);
}
downRemoteViews=new HashMap<>();
downNotification=new HashMap<>();
}
/**
* Refresh the state of the sleepy stuff. This will either show a notification if a notification
* should be shown, or stop the service if it shouldn't.
*/
public void refreshState() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? powerManager.isInteractive() : powerManager.isScreenOn()) {
AlarmData nextAlarm = getSleepyAlarm(alarmio);
if (nextAlarm != null) {
NotificationCompat.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null)
manager.createNotificationChannel(new NotificationChannel("sleepReminder", getString(R.string.title_sleep_reminder), NotificationManager.IMPORTANCE_DEFAULT));
builder = new NotificationCompat.Builder(this, "sleepReminder");
} else builder = new NotificationCompat.Builder(this);
startForeground(540, builder.setContentTitle(getString(R.string.title_sleep_reminder))
.setContentText(String.format(getString(R.string.msg_sleep_reminder),
FormatUtils.formatUnit(this, (int) TimeUnit.MILLISECONDS.toMinutes(nextAlarm.getNext().getTimeInMillis() - System.currentTimeMillis()))))
.setSmallIcon(R.drawable.ic_notification_sleep)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build());
return;
}
}
stopForeground(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
stopSelf();
}
private void sendIconNumNotification() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (nm == null) return;
String notificationChannelId = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = createNotificationChannel();
nm.createNotificationChannel(notificationChannel);
notificationChannelId = notificationChannel.getId();
}
Notification notification = null;
try {
notification = new NotificationCompat.Builder(this, notificationChannelId)
.setSmallIcon(getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle("title")
.setContentText("content num: " + count)
.setTicker("ticker")
.setAutoCancel(true)
.setNumber(count)
.build();
notification = setIconBadgeNumManager.setIconBadgeNum(getApplication(), notification, count);
nm.notify(32154, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createChannelAndHandleNotifications(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(NOTIFICATION_CHANNEL_DESCRIPTION);
channel.setShowBadge(true);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationsManager.handleNotifications(context, DemoNotificationsHandler.class);
}
}
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onCreateNotificationChannel(@NonNull NotificationManager notificationManager) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_PROGRESS,
getString(R.string.notification_channel_progress_message),
NotificationManager.IMPORTANCE_LOW);
channel.enableLights(false);
channel.enableVibration(false);
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
@Override
public void onCreate() {
context = getApplicationContext();
pendingJobs = new ArrayList<>();
SharedPreferences preferences = getSharedPreferences("appSettings",MODE_PRIVATE);
useFFMPEGmuxer = preferences.getBoolean("pref_muxer",true);
PRDownloader.initialize(context);
/** Create notification channel if not present */
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel("channel_01", name, importance);
notificationChannel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"Download",importance);
notificationManager.createNotificationChannel(channel);
}
/** Setting Power Manager and Wakelock */
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "app:Wakelock");
wakeLock.acquire();
Intent notificationIntent = new Intent(context, DownloadActivity.class);
contentIntent = PendingIntent.getActivity(context,
0, notificationIntent, 0);
Intent newintent = new Intent(context, SongBroadCast.class);
newintent.setAction("com.kpstv.youtube.STOP_SERVICE");
cancelIntent =
PendingIntent.getBroadcast(context, 5, newintent, 0);
setUpdateNotificationTask();
super.onCreate();
}
public void sendNotification() {
Intent mainIntent = new Intent(this, MainActivity.class);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notifications";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setSound(null, null);
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("We Miss You!")
.setContentText("Please clear your WhatsApp Media Clutter.")
.setTicker("We Miss You! Please Clear Your WhatsApp Media Clutter.")
.setChannelId(CHANNEL_ID)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setSound(null)
.setLights(Color.GREEN, 3000, 3000)
.setColor(Color.parseColor("#12921F"))
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setAutoCancel(true);
notificationManager.createNotificationChannel(mChannel);
notificationManager.notify(notificationId, notificationBuilder.build()); Log.v(TAG, "Notification sent");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("We Miss You!")
.setContentText("Please clear your WhatsApp Media Clutter.")
.setTicker("We Miss You! Please Clear Your WhatsApp Media Clutter.")
.setPriority(NotificationManager.IMPORTANCE_DEFAULT)
.setSound(null)
.setLights(Color.GREEN, 3000, 3000)
.setColor(Color.parseColor("#12921F"))
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setAutoCancel(true);
notificationManager.notify(notificationId, notificationBuilder.build());
Log.v(TAG, "Notification sent");
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("We Miss You!")
.setContentText("Please clear your WhatsApp Media Clutter.")
.setTicker("We Miss You! Please Clear Your WhatsApp Media Clutter.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(null)
.setLights(Color.GREEN, 3000, 3000)
.setColor(Color.parseColor("#12921F"))
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setAutoCancel(true);
notificationManager.notify(notificationId, notificationBuilder.build());
Log.v(TAG, "Notification sent");
}
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_DEFAULT_CHANNEL_ID, getString(R.string.notification_channel_name), NotificationManagerCompat.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setOnAudioFocusChangeListener(audioFocusChangeListener)
.setAcceptsDelayedFocusGain(false)
.setWillPauseWhenDucked(true)
.setAudioAttributes(audioAttributes)
.build();
}
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mediaSession = new MediaSessionCompat(this, "PlayerService");
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setCallback(mediaSessionCallback);
Context appContext = getApplicationContext();
Intent activityIntent = new Intent(appContext, MainActivity.class);
mediaSession.setSessionActivity(PendingIntent.getActivity(appContext, 0, activityIntent, 0));
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null, appContext, MediaButtonReceiver.class);
mediaSession.setMediaButtonReceiver(PendingIntent.getBroadcast(appContext, 0, mediaButtonIntent, 0));
exoPlayer = ExoPlayerFactory.newSimpleInstance(this, new DefaultRenderersFactory(this), new DefaultTrackSelector(), new DefaultLoadControl());
exoPlayer.addListener(exoPlayerListener);
DataSource.Factory httpDataSourceFactory = new OkHttpDataSourceFactory(new OkHttpClient(), Util.getUserAgent(this, getString(R.string.app_name)));
Cache cache = new SimpleCache(new File(this.getCacheDir().getAbsolutePath() + "/exoplayer"), new LeastRecentlyUsedCacheEvictor(1024 * 1024 * 100)); // 100 Mb max
this.dataSourceFactory = new CacheDataSourceFactory(cache, httpDataSourceFactory, CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
this.extractorsFactory = new DefaultExtractorsFactory();
}
private NotificationCompat.Builder setupNotification() {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "foreground_scanner_channel";
if (Build.VERSION.SDK_INT >= 26) {
CharSequence channelName = "RuuviStation foreground scanner";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
try {
notificationManager.createNotificationChannel(notificationChannel);
} catch (Exception e) {
Log.e(TAG, "Could not create notification channel");
}
}
Intent notificationIntent = new Intent(this, StartupActivity.class);
Bitmap bitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
String notificationText = getString(R.string.scanner_notification_title);
notificationText = notificationText.replace("..", " every ");
int scanInterval = new Preferences(getApplicationContext()).getBackgroundScanInterval();
int min = scanInterval / 60;
int sec = scanInterval - min * 60;
if (min > 0) {
String minutes = getString(R.string.minutes).toLowerCase();
if (min == 1) {
minutes = minutes.substring(0, minutes.length() - 1);
}
notificationText += min + " " + minutes + ", ";
}
if (sec > 0) {
String seconds = getString(R.string.seconds).toLowerCase();
if (sec == 1) {
seconds = seconds.substring(0, seconds.length() - 1);
}
notificationText += sec + " " + seconds;
}
else {
notificationText = notificationText.replace(", ", "");
}
notification
= new NotificationCompat.Builder(getApplicationContext(), channelId)
.setContentTitle(notificationText)
.setSmallIcon(R.mipmap.ic_launcher_small)
.setTicker(this.getString(R.string.scanner_notification_ticker))
.setStyle(new NotificationCompat.BigTextStyle().bigText(this.getString(R.string.scanner_notification_message)))
.setContentText(this.getString(R.string.scanner_notification_message))
.setOnlyAlertOnce(true)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setLargeIcon(bitmap)
.setContentIntent(pendingIntent);
notification.setSmallIcon(R.drawable.ic_ruuvi_bgscan_icon);
return notification;
}