在 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);
}
更新:
NotificationCompat.Builder reference
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.+"
来源Android Developers Channel on Youtube
另外,您可以查看official Android Docs