我目前正在尝试在我的应用程序中实现一个推送通知,一旦有了互联网连接,它就会被发送。 用于检查连接的服务工作正常,并且正在调用showNotifications()方法。 但通知不会出现在酒吧里。 这是代码:
private void showNotifications(){
Intent intent = new Intent(APITest2.this, Start.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("notif","notify");
PendingIntent contentIntent = PendingIntent.getActivity(APITest2.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder= new NotificationCompat.Builder(APITest2.this)
.setSmallIcon(R.drawable.ic_android)
.setContentTitle("Title")
.setContentText("Text")
.setAutoCancel(true);
builder.setContentIntent(contentIntent);
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,builder.build());
}
我是不是漏掉了什么?
提前感谢您的任何帮助!
使用如下所示的通知管理器来支持所有android版本
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.package.name");
NotificationChannel channel = new NotificationChannel(
"com.package.name",
"AppName",
NotificationManager.IMPORTANCE_HIGH
);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
notificationManager.notify(0, builder.build());
像下面这样创建频道,
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
String characterSequence = "Message Alert";
NotificationChannel channel = new NotificationChannel(channelId,
characterSequence,NotificationManager.IMPORTANCE_DEFAULT);
channel.setSound(soundUri,audioAttributes );
NotificationManager manager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
您需要像下面这样在这里传递频道id,
NotificationCompat.Builder builder= new NotificationCompat.Builder(APITest2.this,channelId)
另请参阅https://developer.android.com/training/notify-user/channels
如果您需要显示heads up通知,那么您需要将通知通道中的重要性级别设置为importance_high。 并且需要在notification builder中设置优先级,如下所示。
setPriority(NotificationCompat.PRIORITY_HIGH);