Android Oreoから通知を送るにはまずチャンネルを登録するようになった。
https://feel-log.net/android/developer/o-notification-no-sound-vibration/
int importance = NotificationManager.IMPORTANCE_;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
NotificationManager manager =
(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
一度作成すると、同じIDで重要度を以前より高くできない。
画面の設定(表示文字) Android 8.0 / 8.1 | 画面の設定(表示文字) Android 9 | NotificationManager の定数 | 振る舞い |
---|---|---|---|
重要度(非常に高い) / 緊急 | 音声とポップアップで知らせる | IMPORTANCE_HIGH | ヘッドアップ通知 音・バイブレーションあり※1 |
高 | 音声で知らせる | IMPORTANCE_DEFAULT | 通知 音・バイブレーションあり※1 |
重要度(中) / 中 | マナーモードで表示する | IMPORTANCE_LOW | 通知 音・バイブレーションなし |
低 | マナーモードで表示し最小化 | IMPORTANCE_MIN | 通知(アイコンなし) |
※1:通知音・バイブレーションはありが基本ですが、あえてオフにしたい場合は次のようにしてください。
- 通知音をオフにしたい場合、NotificationChannel.setSound(Uri, AudioAttributes)でサイレントの音源を設定
- バイブレーションをオフにしたい場合、NotificationChannnel.enableVibration(false)を実行
val remoteViews = RemoteViews(getApplicationContext().packageName, R.layout.notification_heads_up_news)
remoteViews.setTextViewText(R.id.message, message)
return NotificationCompat.Builder(mContext, channelId)
.setSmallIcon(R.drawable.ic_notification_simple)
.setColor(ContextCompat.getColor(mContext, R.color.colorGoo))
.setContentTitle(title)
.setContentText(message)
.setSubText(message)
.setAutoCancel(true)
.setCustomHeadsUpContentView(remoteViews)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(pendingIntent)
RemoteViews Viewと結構違うので注意
サンプル
private void normalNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(R.drawable.ic_notification);
builder.setContentTitle("タイトル");
builder.setContentText("内容");
builder.setContentInfo("情報欄");
builder.setTicker("通知概要");
NotificationManager manager =
(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
private void launcherAppNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(R.drawable.ic_notification);
builder.setContentTitle("タップでアプリを起動する");
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
NotificationManager manager = (NotificationManager)
getSystemService(Service.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}