ともちゃんのAndroid開発日記

組込みC言語プログラマだったともちゃんが、四苦八苦しながら、AndroidのJAVAとKotlinを習得して行きます。ともちゃんの備忘録も兼ねています。

Android 8.0の通知(NotificationChannel)

Android 8.0では、通知にNotificationChannelを設定してやる必要があります。

NotificationManager myNotification = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(DEFAULT_CHANNEL,
resources.getString(R.string.notification_medicine_time),
NotificationManager.IMPORTANCE_DEFAULT);
/* 指定できる値は以下7種類。
NotificationManager.IMPORTANCE_UNSPECIFIED (-1000);
NotificationManager.IMPORTANCE_NONE (0);
NotificationManager.IMPORTANCE_MIN (1);
NotificationManager.IMPORTANCE_LOW (2);
NotificationManager.IMPORTANCE_DEFAULT (3);
NotificationManager.IMPORTANCE_HIGH (4);
NotificationManager.IMPORTANCE_MAX (5);
*/
myNotification.createNotificationChannel(channel);
}
Intent intent = new Intent(context, TakingCheckActivity.class);
intent.putExtra("user", user_id);
intent.putExtra("taking_timing", taking_timing);
intent.putExtra("time_in_millis", time_in_millis);
intent.setType(message);
Intent bootIntent[] = {intent};
PendingIntent contentIntent = PendingIntent.getActivities(context, notification_id, bootIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(context, DEFAULT_CHANNEL);
} else {
builder = new Notification.Builder(context);
}
builder.setSmallIcon(R.drawable.notification_small_icon)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.notification_large_icon))
.setContentTitle(resources.getString(R.string.notification_message_1))
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setSound(uri)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setContentIntent(contentIntent);

myNotification.notify(notification_id, builder.build());