Normal Notification Builder doesn't show notifications on Android O.
How could I show notification on Android 8 Oreo?
Is there any new piece of code to add for showing notification on Android O?
ベストアンサー1
In Android O it's a must to use a channel通知ビルダーで
以下はサンプルコードです:
// 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 リファレンス
NotificationCompat.Builder(Context context)
このコンストラクタはAPIレベル26.0.0で非推奨になったため、
Builder(Context context, String channelId)
setChannelId
したがって、新しいコンストラクターを使用する必要はありません。
そして、現在26.0.2である最新のAppCompatライブラリを使用する必要があります。
compile "com.android.support:appcompat-v7:26.0.+"
また、確認することもできます公式 Android ドキュメント