Android 自定义通知栏前台服务-通知栏点击事件

先说明一下,通知栏这个功能,我一般用的很少,故不是太熟悉,今天有这个需求,前台service常驻,自义定的通知栏带点击事件跳转,搞了一两个小时,设置的点击事件一直不起作用。郁闷了半天最后才发现问题。下面代码贴出来介绍。

// 唯一的通知通道的id , 设置的成员变量
    String notificationChannelId = "notification_channel_id_01";
    private void createNotific(){
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //2.初始化一个notification的对象
        Notification.Builder builder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0 通知栏专属
            NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId,"我的应用名称",NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(notificationChannel);
            builder.setChannelId(notificationChannelId);
        }
        // 自定义通知栏样式用到RemoteViews ,第一个参数固定写法,第二个布局id
        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.service_notific_layout);
        // 设置点击事件 1  
        Intent cleatInt = new Intent(this, AAAAActivity.class);
        cleatInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent clearIntent = PendingIntent.getActivity(this,0,cleatInt,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.imgToClear,clearIntent);
        // 设置点击事件 2  
        Intent speedInt = new Intent(this, BBBBActivity.class);
        speedInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent speedIntent = PendingIntent.getActivity(this,12,speedInt,0);
        remoteViews.setOnClickPendingIntent(R.id.imgToSpeed,speedIntent);
          //这里把布局 设置到Content中
        builder.setContent(remoteViews);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Notification notification = builder.build();
        notificationManager.notify(NOTIFICATION_ID,notification);
        // 前台服务方式 必备
        startForeground(NOTIFICATION_ID,notification);

    }

重要--重要--重要

看到上面代码了吧,有一个顺序问题,就是通知PendingIntent 设置的点击跳转,一定要放在          

//这里把布局 设置到Content中
builder.setContent(remoteViews);

这句代码前面

否则点击事件不起任何作用。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值