我已经阅读了大多数与此相关的问题/答案,但是我的通知仍然没有显示。
我的广播接收器被呼叫,但是什么也没发生。没有错误消息也没有异常。这是我的代码:
public class AlarmReceiver extends BroadcastReceiver {
private static int notificationId = 0;
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "mychannel")
.setSmallIcon(R.drawable.icon_awake)
.setContentTitle("MyAlarm")
.setContentText("Something")
.setAutoCancel(false)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId++, mNotifyBuilder.build());
}
}
答案 0 :(得分:1)
我认为您忘记了在Oreo 8.0上阅读Google文档。 如果要在8.0上创建通知,则需要使用 NotificationChannel
像这样:
NotificationChannel channel = null;
String chanel = "MY_Musixbox";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
channel = new NotificationChannel(chanel, "MusicBox", importance);
notificationManager.createNotificationChannel(channel);
}
然后添加您的通知
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "mychannel")
.setSmallIcon(R.drawable.icon_awake)
.setContentTitle("MyAlarm")
.setContentText("Something")
.setChannelId(chanel);
.setAutoCancel(false)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId++, mNotifyBuilder.build());
答案 1 :(得分:0)
好的,所以我会自己回答,以防万一有人找到它:看来您也需要自己手动创建通知渠道:
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel("mychannel",
"Channel name",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Channel description");
notificationManager.createNotificationChannel(channel);
}
答案 2 :(得分:0)
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "mychannel")
.setSmallIcon(R.drawable.icon_awake)
.setContentTitle("MyAlarm")
.setContentText("Something")
.setAutoCancel(false)
.setWhen(System.currentTimeMillis())
.setChannelId("default_channel")
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId++, mNotifyBuilder.build());
尝试一下。您必须定义频道ID。多数民众赞成在android 8.0中是必须的