android 5.0以上使用Notification

话不多说,直接上代码,这是发送通知并且,点击通知发送一个广播,适合不跳转页面的情况,需要跳转页面请往下看。

    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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值