先上效果图
参考这篇文章解决
/**
* 发送通知
* @param content
*/
@SuppressLint("WrongConstant")
private void sendNotification(String content) {
try {
String[] contents = content.split(",");
Intent intent = new Intent();
intent.setClass(this, TabHostActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationManager notifiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = getPackageName();
String name = "call_msg";
//Android 8.0 的要手动设置NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//NotificationManager.IMPORTANCE_MAX 最高支持 声音和悬浮
NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_MAX);
notifiManager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.pre_icon)
.setContentTitle(contents[0])
.setContentText(contents[1])
.setVisibility(VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
//向通知添加声音、闪灯和振动效果
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent)
.setChannelId(id)
.build();
notifiManager.notify(1, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
主要适配sdk26(Android 8.0)之后的
然后使用.setChannelId(id)方法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//NotificationManager.IMPORTANCE_MAX 最高支持 声音和悬浮
NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_MAX);
notifiManager.createNotificationChannel(channel);
}