话不多说,直接上代码,这是发送通知并且,点击通知发送一个广播,适合不跳转页面的情况,需要跳转页面请往下看。
private static final int PUSH_NOTIFICATION_ID = (0x001);
private static final String PUSH_CHANNEL_ID = "PUSH_NOTIFY_ID";
private static final String PUSH_CHANNEL_NAME = "PUSH_NOTIFY_NAME";
private void sendNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(PUSH_CHANNEL_ID, PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
Notification.Builder builder = new Notification.Builder(this, PUSH_CHANNEL_ID);
Intent notificationIntent = new Intent("open_dvd_action");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle("通知标题")//设置通知栏标题
.setContentIntent(pendingIntent) //设置通知栏点击意图
.setContentText("通知内容")
.setTicker("通知内容") //通知首次出现在通知栏,带上升动画效果的
.setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
.setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if (notificationManager != null) {
notificationManager.notify(PUSH_NOTIFICATION_ID, notification);
}
}
如果需要点击通知跳转页面的话,将上面的Intent和PendingIntent做下修改即可,如下
Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
另外还有一点,发送通知时,是否在页面顶部弹出,可以通过对上面方法中
NotificationManager.IMPORTANCE_HIGH 进行修改,具体定义如下
紧急级别(发出通知声音并显示为提示通知)
8.0及以上:IMPORTANCE_HIGH
8.0以下:PRIORITY_HIGH或者PRIORITY_MAX
高级别(发出通知声音并且通知栏有通知)
8.0及以上:IMPORTANCE_DEFAULT
8.0以下:PRIORITY_DEFAULT
中等级别(没有通知声音但通知栏有通知)
8.0及以上:IMPORTANCE_LOW
8.0以下:PRIORITY_LOW
低级别(没有通知声音也不会出现在状态栏上)
8.0及以上:IMPORTANCE_MIN
8.0以下:PRIORIT