Android Notification的基本使用
这篇很详细:https://blog.youkuaiyun.com/dsc114/article/details/51721472
以下是自己亲测可用的情况:支持8.0 Notification Channel
Notification的使用大体步骤:
1、 获取状态通知栏管理
2、 实例化通知栏构造器
3、 设置NotificationCompat.Builder
4、 设置PendingIntent
5、 显示
private void showNotification(Context context){
final String CHANNEL_ID = "channel_id_1";
final String CHANNEL_NAME = "channel_name_1";
//获取状态通知栏管理
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//8/0处理
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//只在Android O之上需要渠道
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
//相关api设置,基本用不到
notificationChannel.canBypassDnd();//可否绕过请勿打扰模式
notificationChannel.enableLights(true);//闪光
notificationChannel.setLockscreenVisibility(VISIVILITY_SECRET);//锁屏显示通知
notificationChannel.setLightColor(Color.RED)://闪光颜色
notificationChannel.canShowBadge();//桌面laucher消息角标
notificationChannel.getAudioAttributes();//获取系统通知响铃声音的配置
notificationChannel.getGroup();//获取通知渠道组
notificationChannel.settBypassDnd(true);//设置可以绕过,请勿打扰模式
notificationChannel.setVibrationPattern(new long[]{100,100,200});//震动的模式
notificationChannel.shouldShowLights();//是否会闪灯光
//如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道,
//通知才能正常弹出
mNotificationManager.createNotificationChannel(notificationChannel);
}//实例化通知栏构造器
NotificationCompat.Builder builder= new NotificationCompat.Builder(context,CHANNEL_ID);
//设置PendingIntent
Intent intent = new Intent(context, Main2Activity.class); //需要跳转指定的页面
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("通知标题")
.setContentText("通知内容")
.setContentIntent(pendingIntent)
.setAutoCancel(true);
//显示
mNotificationManager.notify(0, builder.build());
}
源码地址:https://download.youkuaiyun.com/download/silence_sep/10435392