在 Android O 中是必须使用渠道与您的通知生成器
下面是示例代码:
// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
或者通过以下方式处理兼容性:
NotificationCompat notification =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setChannelId(CHANNEL_ID).build();
现在让它通知
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
或者,如果您想要简单的修复,请使用以下代码:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationManager.createNotificationChannel(mChannel);
}
Updates:
NotificationCompat.Builder 参考
NotificationCompat.Builder(Context context)
此构造函数在 API 级别 26.0.0 中已弃用
所以你应该使用
Builder(Context context, String channelId)
所以没必要setChannelId
使用新的构造函数。
并且您应该使用当前最新的 AppCompat 库 26.0.2
compile "com.android.support:appcompat-v7:26.0.+"
来源自YouTube 上的 Android 开发者频道
另外,你可以检查官方 Android 文档