通知栏的创建
在Android设备上如果要实现通知栏功能,需要区分系统版本,因为大于等于Android 8.0系统的和之前版本使用的方式不一致,故需要加版本区分代码:
//构建通知栏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //8.0
createApi26();
} else {
createNormal();
}
- 创建正常的通知栏
/**
* 创建8.0以下的ui
*/
@SuppressWarnings("all")
private void createNormal() {
if (mBuilder == null) {
mBuilder = new NotificationCompat.Builder(mContext);
}
if (notification != null) {
notification = null;
}
mBuilder
// .setContent(mNormalRemoteViews)
.setCustomContentView(mSmallNormalRemoteViews)
.setCustomBigContentView(mNormalRemoteViews)
.setSmallIcon(R.drawable.ic_launcher)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true)
.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);
notification = mBuilder.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
- Android 8.0版本及以后的创建方式:
/**
* 8.0以上创建通知栏
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private void createApi26() {
if (manager == null) return;
if (mChannel == null) {
mChannel = new NotificationChannel(mChannelId, mChannelName,
NotificationManager.IMPORTANCE_HIGH);
}
manager.createNotificationChannel(mChannel);
if (notification != null) {
notification = null;
}
notification = new NotificationCompat.Builder(mContext, mChannelId)
// .setContent(mNormalRemoteViews)
.setCustomContentView(mSmallNormalRemoteViews)
.setCustomBigContentView(mNormalRemoteViews)
.setShowWhen(true)
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
- 展示和取消通知栏的方式
//展示通知栏
manager.notify(notifycatonid, notification);
//取消通知栏
manager.cancel(notifycatonid);
- 开启一个service并且调用startForeground方法,可以提升app的存活率
startForeground(NOTICE_ID, notification);
网友评论