Android 8.0 通知适配:
Android Api 26 Notification Builder 构建方法 Builder(Context contenxt) 已弃用 Builder创建时要传入Notifications or NotificationChannel Id
/**
* @deprecated use {@link Notification.Builder#Notification.Builder(Context, String)}
* instead. All posted Notifications must specify a NotificationChannel Id.
*/
@Deprecated
public Builder(Context context) {
this(context, (Notification) null);
}
创建 NotificationChannel 对象
/**
* Creates a notification channel.
*
* @param id The id of the channel. Must be unique per package. The value may be truncated if
* it is too long. ps: 每个app包下的Id 必须是唯一的
* @param name The user visible name of the channel. You can rename this channel when the system
* locale changes by listening for the {@link Intent#ACTION_LOCALE_CHANGED}
* broadcast. The recommended maximum length is 40 characters; the value may be
* truncated if it is too long.
* @param importance The importance of the channel. This controls how interruptive notifications
* posted to this channel are.
*/
public NotificationChannel(String id, CharSequence name, @Importance int importance) {
this.mId = getTrimmedString(id);
this.mName = name != null ? getTrimmedString(name.toString()) : null;
this.mImportance = importance;
}
/**
* 通知内容
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void noticeEightInit(@NonNull String msg) {
this.noticeEightInit(msg, null);
}
/**
* 通知内容
*
* @param msg
* @param intent
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void noticeEightInit(String msg, Intent intent) {
Notification.Builder builder = new Notification.Builder(mContext, "1");
builder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_logo));
builder.setSmallIcon(R.drawable.ic_logo);
builder.setPriority(Notification.PRIORITY_DEFAULT);
builder.setCategory(Notification.CATEGORY_MESSAGE);
builder.setAutoCancel(true); //自动消失
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle("测试通知");
builder.setContentText(msg);
builder.setSubText("测试通知");
if (intent != null) {
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setFullScreenIntent(pendingIntent, true);
}
NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
//ChannelId为"1",ChannelName为"Channel_One"
NotificationChannel channel = new NotificationChannel("1",
"Channel_One", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小红点
channel.setLightColor(Color.RED); //小红点颜色
channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
manager.createNotificationChannel(channel);
manager.notify(1, builder.build());
}