发现8.0以上系统有一个消息通道的概念,在需要发布消息通知之前必须需要一个消息通道。接下来创建消息通道
private NotificationManager notificationManager;
private Notification notification;
private static final String CHANNEL_ID="channel_id"; //通道渠道id
public static final String CHANEL_NAME="chanel_name"; //通道渠道名称
NotificationChannel channel = null;
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
//创建 通知通道 channelid和channelname是必须的(自己命名就好)
channel = new NotificationChannel(CHANNEL_ID, CHANEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);//是否在桌面icon右上角展示小红点
channel.setLightColor(Color.GREEN);//小红点颜色
channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
}
// 跳转的Activity
Intent intent = new Intent(TheApp.instance, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(TheApp.instance, 0, intent, 0);
if(notificationManager == null){
//创建一个通知管理器
notificationManager= (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
notificationManager.createNotificationChannel(channel);
}
// notificationManager = (NotificationManager) TheApp.instance.getSystemService(NOTIFICATION_SERVICE);
}
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
//向上兼容 用Notification.Builder构造notification对象
notification = new Notification.Builder(MQTTService.this,CHANNEL_ID)
.setContentText("MQTT消息:" + str1)
.setContentTitle("MQTT推送")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.icon_144)
/** 响铃震动 */
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.FLAG_AUTO_CANCEL )
.setAutoCancel(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.build();
}else {
notification = new NotificationCompat.Builder(MQTTService.this)
.setAutoCancel(true)
.setContentText("MQTT消息:" + str1)
.setContentTitle("MQTT推送")
.setSmallIcon(R.drawable.icon_144)
/** 响铃震动 */
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.FLAG_AUTO_CANCEL )
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
}
notificationManager.notify((int)(System.currentTimeMillis()/1000),notification);