Android 8 (Oreo) 以降の通知生成

久々に Google Play へ登録したアプリを更新しようとしたら、targetSdkVersion は 26 以上、2019/11/1以降は 28 以上じゃないとアップできねーとか表示されて、ターゲットをあげた途端に色々動作しなくなったり強制終了するようになったのメモ

Oreo以降の通知登録、Notification.Builder へ setChannelId を追加と NotificationChannel の利用が必須へ

Android 8 (Oreo) 以降の通知生成
(わかりにくいので括弧で包んでます)

  1. // 通知をタップで起動するActivity  
  2. Intent intent = new Intent(this, HogeActivity.class); // タップで呼ばれるActivity  
  3. intent.putExtra("sendData"true); // Activityへ渡すデータ等(複数追加可)  
  4.   
  5. PendingIntent contentIntent = PendingIntent.getActivity(this0, intent, PendingIntent.FLAG_CANCEL_CURRENT);  
  6.   
  7. // 通知生成  
  8. NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  9. {  
  10.     Notification.Builder nbuilder = new Notification.Builder(this);  
  11.     {  
  12.         nbuilder.setPriority(Notification.PRIORITY_DEFAULT);  
  13.         nbuilder.setContentTitle("タイトル");  
  14.         nbuilder.setContentText("メッセージ");  
  15.         // nbuilder.setAutoCancel(true); // タップしたら解除  
  16.         nbuilder.setSmallIcon(R.drawable.ic_hogehoge); // アイコン  
  17.         nbuilder.setOngoing(true); // 削除不可  
  18.         nbuilder.setContentIntent(contentIntent);  
  19.   
  20.         // 8(Oreo) API26 以降  
  21.         if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {  
  22.             nbuilder.setChannelId("hogehoge_channgel_01");  
  23.         }  
  24.     }  
  25.   
  26.     // 8(Oreo) API26 以降  
  27.     if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {  
  28.         NotificationChannel channel = new NotificationChannel("hogehoge_channgel_01""hogehoge channel", NotificationManager.IMPORTANCE_HIGH); //Create Notification Channel  
  29.         channel.setDescription("Channel Description.");  
  30.         nManager.createNotificationChannel(channel);  
  31.     }  
  32.   
  33.     nManager.notify(0/* 削除等に利用する番号 */, nbuilder.build()); // NotificationManagerに登録  
  34. }  

コメント