先说明一下,通知栏这个功能,我一般用的很少,故不是太熟悉,今天有这个需求,前台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);
这句代码前面
否则点击事件不起任何作用。