通知を作成する

通知は、アプリが使用されていないときに、アプリ内のイベントに関する簡潔な情報をタイムリーに提供します。このドキュメントでは、Google Chat で 使用できます。Android での通知の表示方法の概要については、 通知の概要をご覧ください。 通知を使用するサンプルコードについては、 サンプル ご覧ください。

このページのコードでは、AndroidX ライブラリの NotificationCompat API を使用しています。これらの API を使用すると、 Android との下位互換性を維持しつつ、新しいバージョンの Android に対応できます。 9(API レベル 28)です。ただし、インライン返信アクションなどの一部の機能は、 それより前のバージョンでは何も行われません。

AndroidX コアライブラリを追加する

Android Studio で作成されたほとん���のプロジェクトには、 NotificationCompat を使用するには、モジュール レベルのモジュール レベルの build.gradle ファイルには、次の依存関係が含まれています。

Groovy

dependencies {
    implementation "androidx.core:core:2.2.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:2.2.0")
}

基本的な通知を作成する

最も基本的でコンパクトな形式(折りたたみとも呼ばれます)の通知 form - アイコン、タイトル、少量のテキスト コンテンツを表示します。この は、ユーザーがタップして起動できる通知を作成する方法を示しています。 確認できます。

図 1. 通知と アイコン、タイトル、テキストで構成されます。

通知を構成する各要素の詳細については、通知の構造をご覧ください。

実行時の権限を宣言する

Android 13(API レベル 33)以降では、投稿に関する実行時の権限がサポートされています 免除対象外(フォアグラウンド サービス(FGS)を含む)の通知をアプリから送信する場合。

アプリのマニフェスト ファイルで宣言する必要がある権限が これを次のコード スニペットに示します。

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <application ...>
        ...
    </application>
</manifest>

実行時の権限について詳しくは、このモジュールの 通知に関する実行時の権限

通知のコンテンツを設定する

開始するには、 NotificationCompat.Builder 渡されます。次の例は、次を含む通知を作成する方法を示しています。 次の���おりです。

  • 小さなアイコン。 setSmallIcon()。 これは、ユーザーに表示されるコンテンツのうち、唯一必須な要素です。

  • タイトル setContentTitle()

  • 本文のテキスト。 setContentText()

  • 通知の優先度。 setPriority()。 優先度によって、Android 7.1 での通知の煩わしさが決まります。 挙げられますAndroid 8.0 以降では、代わりにチャンネルの重要度を 見てみましょう。

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationCompat.Builder コンストラクタにはチャンネルを指定する必要があります。 あります。これは Android 8.0(API レベル 26)以降との互換性のために必要ですが、それより前のバージョンでは無視されます。

デフォルトでは、通知のテキスト コンテンツは 1 行に収まるように切り捨てられます。マイページ 展開可能な通知を作成して、追加情報を表示できます。

図 2. エキスパンド 通知が折りたたまれたフォームと開かれたフォームに表示されます。

通知で長いテキストを使用したい場合は、setStyle() でスタイル テンプレートを追加して、展開可能な通知を有効にします。たとえば、次のコードはより大きなテキスト領域を作成します。

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(new NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

その他の大きな通知スタイルの詳細( 画像とメディア再生コントロールについて詳しくは、エキスパンド広告を作成する 通知をご覧ください。

チャネルを作成して重要度を設定する

Android 8.0 以降で通知を配信するには、事前に アプリの通知チャンネルと 渡すことにより、システム内の NotificationChannelcreateNotificationChannel()。 次のコードは、SDK_INT バージョンの条件によってブロックされます。

Kotlin

private fun createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is not in the Support Library.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system.
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

Java

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is not in the Support Library.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this.
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

送信する前に通知チャンネルを作成する必要があるため 使用する場合は、アプリが稼働したらすぐにこのコードを実行してください。 開始されます。これは繰り返し呼び出すのが安全です。すでに作成されている 通知チャンネルはオペレーションを実行しません。

NotificationChannel コンストラクタには importance が必要です。これは、 定数の NotificationManager クラス。この によって、通知が通知された場合にユーザーに割り込みする方法が決まります。 おすすめしますsetPriority()優先度を設定し、Android 7.1 をサポートするようにしました それより前のバージョンを付与できます。

通知の重要度や優先度は、 ただし、アラートが確実に動作するとは限りません。イン 他の要因に基づいて重要度が変化することもあります ユーザーはいつでも特定のトピックの重要度を 。

各レベルの意味については、 通知の重要度 。

通知のタップ アクションを設定する

通知はすべてタップに反応する必要があります。通常は、アプリ内でアクティビティを開くために、 返すことができます。そのためには、コンテンツ インテントを指定します。 PendingIntent で定義 そのオブジェクトを取得し、 setContentIntent()

次のスニペットは、アクティビティを開く基本的なインテントを作成する方法を示しています。 ユーザーが通知をタップしたとき:

Kotlin

// Create an explicit intent for an Activity in your app.
val intent = Intent(this, AlertDetails::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that fires when the user taps the notification.
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)

Java

// Create an explicit intent for an Activity in your app.
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that fires when the user taps the notification.
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

このコードは以下を呼び出します。 setAutoCancel() これにより、ユーザーが通知をタップすると、自動的に通知が削除されます。

setFlags() メソッド ユーザーの期待するナビゲーションが維持される ユーザーが通知からアプリを開いたときに表示されます。おすすめ 開始するアクティビティのタイプに応じて 次のとおりです。

  • 通知に応答するためにのみ存在するアクティビティ。 通常のアプリの使用中、ユーザーがこのアクティビティに移動する理由はない。 その場合、アクティビティはアプリの 既存のタスクを スタックしています。これは、上の例で作成されたインテントのタイプです。

  • アプリの通常のアプリフロー内に存在するアクティビティ。この例では アクティビティを開始するとバックスタックが作成され、 [戻る] ボタンと [上へ] ボタンの 保持されます。

通知のインテントを構成するさまざまな方法について詳しくは、以下をご覧ください。 通知からアクティビティを開始する

通知を表示する

通知を表示するには、 NotificationManagerCompat.notify() イベント通知の一意の ID と、 NotificationCompat.Builder.build()。 これを次の例に示します。

Kotlin

with(NotificationManagerCompat.from(this)) {
    if (ActivityCompat.checkSelfPermission(
            this@MainActivity,
            Manifest.permission.POST_NOTIFICATIONS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // TODO: Consider calling
        // ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        // public fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
        //                                        grantResults: IntArray)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        return@with
    }
    // notificationId is a unique int for each notification that you must define.
    notify(NOTIFICATION_ID, builder.build())
}

Java

with(NotificationManagerCompat.from(this)) {
   if (ActivityCompat.checkSelfPermission(
           this@MainActivity,
           Manifest.permission.POST_NOTIFICATIONS
       ) != PackageManager.PERMISSION_GRANTED
   ) {
       // TODO: Consider calling
       // ActivityCompat#requestPermissions
       // here to request the missing permissions, and then overriding
       // public void onRequestPermissionsResult(int requestCode, String[] permissions,
       //                                        int[] grantResults)
       // to handle the case where the user grants the permission. See the documentation
       // for ActivityCompat#requestPermissions for more details.

       return
   }
   // notificationId is a unique int for each notification that you must define.
   notify(NOTIFICATION_ID, builder.build())
}

NotificationManagerCompat.notify() に渡す通知 ID を保存します。 これは、ファイルを更新または削除する際に必要となるためです。 通知)。

また、Android 13 以降を搭載したデバイスで基本的な通知をテストするには、通知を手動でオンにするか、通知をリクエストするダイアログを作成します。

アクション ボタンを追加する

通知には、ユーザーが応答するためのアクション ボタンを 3 つまで設定できます。 たとえば、リマインダーをスヌーズしたり、テキスト メッセージに返信したりできます。しかし、これらの アクション ボタンは、ユーザーが 通知をご覧ください。

図 3. 通知と 1 つの操作ボタン。

アクション ボタンを追加するには、PendingIntentaddAction() メソッドを呼び出します。これは、通知のデフォルトのタップ アクションを設定する場合と同様です。ただし、アクティビティを起動する代わりに、バックグラウンドでジョブを実行する BroadcastReceiver を開始するなどの処理を実行でき、アクションはすでに開いているアプリを中断しません。

たとえば、次のコードは、特定の宛先にブロードキャストを送信する方法を示しています。 receive:

Kotlin

val ACTION_SNOOZE = "snooze"

val snoozeIntent = Intent(this, MyBroadcastReceiver::class.java).apply {
    action = ACTION_SNOOZE
    putExtra(EXTRA_NOTIFICATION_ID, 0)
}
val snoozePendingIntent: PendingIntent =
    PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent)

Java

String ACTION_SNOOZE = "snooze"

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

バックグラウンドを実行する BroadcastReceiver のビルドに関する詳細 ブロードキャストの概要をご覧ください。

また、メディア再生ボタン(トラックの一時停止やスキップなど)を含む通知を作成する場合は、メディア コントロールを備えた通知を作成する方法をご覧ください。

ダイレクト返信アクションを追加する

Android 7.0(API レベル 24)で導入されたダイレクト返信アクションでは、 テキストを直接入力できます。その後、テキストがユーザーの アプリを開かずに操作できます。たとえば、ダイレクト返信アクションを使用して、 画面から直接テキスト メッセージに返信したり、タスクリストを更新したりできるようになります。 通知を受け取ります。

図 4. [返信] ボタンをクリックするとテキスト入力が開きます。

ダイレクト返信アクションは、通知内の追加ボタンとして表示され、 テキスト入力を開きます。ユーザーが入力を終了すると、入力したテキストが レスポンスとして指定したインテントに応答し、 追加できます。

返信ボタンを追加する

ダイレクト返信をサポートする通知アクションを作成する手順は次のとおりです。

  1. インスタンスを RemoteInput.Builder 追加できますこのクラスのコンストラクタは、 システムがテキスト入力のキーとして使用する文字列。アプリは後でそのキーを使用して、入力テキストを取得します。

    Kotlin

      // Key for the string that's delivered in the action's intent.
      private val KEY_TEXT_REPLY = "key_text_reply"
      var replyLabel: String = resources.getString(R.string.reply_label)
      var remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run {
          setLabel(replyLabel)
          build()
      }
      

    Java

      // Key for the string that's delivered in the action's intent.
      private static final String KEY_TEXT_REPLY = "key_text_reply";
    
      String replyLabel = getResources().getString(R.string.reply_label);
      RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
              .setLabel(replyLabel)
              .build();
      
  2. 返信アクションの PendingIntent を作成します。

    Kotlin

      // Build a PendingIntent for the reply action to trigger.
      var replyPendingIntent: PendingIntent =
          PendingIntent.getBroadcast(applicationContext,
              conversation.getConversationId(),
              getMessageReplyIntent(conversation.getConversationId()),
              PendingIntent.FLAG_UPDATE_CURRENT)
      

    Java

      // Build a PendingIntent for the reply action to trigger.
      PendingIntent replyPendingIntent =
              PendingIntent.getBroadcast(getApplicationContext(),
                      conversation.getConversationId(),
                      getMessageReplyIntent(conversation.getConversationId()),
                      PendingIntent.FLAG_UPDATE_CURRENT);
      
  3. こちらの RemoteInput オブジェクトをアクションに addRemoteInput()

    Kotlin

      // Create the reply action and add the remote input.
      var action: NotificationCompat.Action =
          NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
              getString(R.string.label), replyPendingIntent)
              .addRemoteInput(remoteInput)
              .build()
      

    Java

      // Create the reply action and add the remote input.
      NotificationCompat.Action action =
              new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
                      getString(R.string.label), replyPendingIntent)
                      .addRemoteInput(remoteInput)
                      .build();
      
  4. アクションを通知に適用し、通知を発行します。

    Kotlin

      // Build the notification and add the action.
      val newMessageNotification = Notification.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_message)
              .setContentTitle(getString(R.string.title))
              .setContentText(getString(R.string.content))
              .addAction(action)
              .build()
    
      // Issue the notification.
      with(NotificationManagerCompat.from(this)) {
          notificationManager.notify(notificationId, newMessageNotification)
      }
      

    Java

      // Build the notification and add the action.
      Notification newMessageNotification = new Notification.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_message)
              .setContentTitle(getString(R.string.title))
              .setContentText(getString(R.string.content))
              .addAction(action)
              .build();
    
      // Issue the notification.
      NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
      notificationManager.notify(notificationId, newMessageNotification);
      

ユーザーがレスポンスの入力を 通知アクションを実行します。

返信からユーザー入力を取得する

通知の返信 UI からユーザー入力を受け取るには、次の呼び出しを呼び出します。 RemoteInput.getResultsFromIntent() BroadcastReceiver が受け取った Intent を渡します。

Kotlin

private fun getMessageText(intent: Intent): CharSequence? {
    return RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_TEXT_REPLY)
}

Java

private CharSequence getMessageText(Intent intent) {
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput != null) {
        return remoteInput.getCharSequence(KEY_TEXT_REPLY);
    }
    return null;
 }

テキストを処理したら、 を呼び出して通知を更新します。 NotificationManagerCompat.notify() を使用する場合は、同じ ID とタグで置き換えます。これは、 ダイレクト リプライの UI を非表示にして、返信内容をユーザーに 正しく受信、処理されます。

Kotlin

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
val repliedNotification = Notification.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_message)
        .setContentText(getString(R.string.replied))
        .build()

// Issue the new notification.
NotificationManagerCompat.from(this).apply {
    notificationManager.notify(notificationId, repliedNotification)
}

Java

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
Notification repliedNotification = new Notification.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_message)
        .setContentText(getString(R.string.replied))
        .build();

// Issue the new notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, repliedNotification);

この新しい通知を使用する場合、レシーバの onReceive() メソッドに渡されるコンテキストを使用します。

setRemoteInputHistory() を呼び出して、通知の下部に返信���追加します。ただし、メッセージ アプリを作成する場合は、メッセージ スタイルの 新着メッセージがあります。

メッセージ アプリからの通知に関するアドバイスについては、 メッセージ アプリに関するおすすめの方法をご覧ください。

進行状況バーを追加する

通知には、進行状況を示すアニメーション インジケーターを含め、 ステータスを記録します。

図 5. オペレーション中の進行状況バー。

どの程度のオペレーションが完了したかをいつでも見積もることができる場合は、 「確定」できます(図 5 を参照)。 setProgress(max, progress, false)。 最初のパラメータは、「完了」する100 などです2 つ目は、 確認できます最後は、これが確定的な進行状況であることを示しています。 表示されます。

オペレーションの進行中に、更新された progress の値で setProgress(max, progress, false) を継続的に呼び出し、次のように通知を再発行します。 表示されます。

Kotlin

val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
    setContentTitle("Picture Download")
    setContentText("Download in progress")
    setSmallIcon(R.drawable.ic_notification)
    setPriority(NotificationCompat.PRIORITY_LOW)
}
val PROGRESS_MAX = 100
val PROGRESS_CURRENT = 0
NotificationManagerCompat.from(this).apply {
    // Issue the initial notification with zero progress.
    builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
    notify(notificationId, builder.build())

    // Do the job that tracks the progress here.
    // Usually, this is in a worker thread.
    // To show progress, update PROGRESS_CURRENT and update the notification with:
    // builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
    // notificationManager.notify(notificationId, builder.build());

    // When done, update the notification once more to remove the progress bar.
    builder.setContentText("Download complete")
            .setProgress(0, 0, false)
    notify(notificationId, builder.build())
}

Java

...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setContentTitle("Picture Download")
        .setContentText("Download in progress")
        .setSmallIcon(R.drawable.ic_notification)
        .setPriority(NotificationCompat.PRIORITY_LOW);

// Issue the initial notification with zero progress.
int PROGRESS_MAX = 100;
int PROGRESS_CURRENT = 0;
builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
notificationManager.notify(notificationId, builder.build());

// Do the job that tracks the progress here.
// Usually, this is in a worker thread.
// To show progress, update PROGRESS_CURRENT and update the notification with:
// builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
// notificationManager.notify(notificationId, builder.build());

// When done, update the notification once more to remove the progress bar.
builder.setContentText("Download complete")
        .setProgress(0,0,false);
notificationManager.notify(notificationId, builder.build());

オペレーションの終了時には、progressmax と等しくなる必要があります。このまま 進行状況バーが表示され、オペレーションの完了を確認したり削除したりできます。いずれの場合も、 通知テキストを更新して、オペレーションが完了したことを示します。進行状況バーを���除するには、setProgress(0, 0, false) を呼び出します。

不確定形式の進行状況バー(完了率を示さないバー)を表示するには、setProgress(0, 0, true) を呼び出します。その結果、 直前の進行状況バーと同じスタイルですが、連続 完了を示さないアニメーションを作成します。進行状況アニメーションは次の時点まで続きます。 setProgress(0, 0, false) を呼び出し、通知を更新して クリックします。

通知テキストは、オペレーションが実行中であることを示すために、 できます。

システムレベルのカテゴリを設定する

Android は、システム全体を対象とする事前定義済みのカテゴリを使用して、ユーザーがサイレント モードを有効にしているときに特定の通知でユーザーの操作に割り込むかどうかを決定します。

通知が NotificationCompat - 例: CATEGORY_ALARM, CATEGORY_REMINDER, CATEGORY_EVENT, または CATEGORY_CALL - 宣言 そのようにするために適切なカテゴリを setCategory():

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE);

システムは、通知カテゴリに関するこの情報を使用して、 デバイスがサイレント モードの場合の通知の表示に関する決定 対応不可。ただし、システム全体のカテゴリを設定する必要はありません。必要な場合のみ によって定義されたカテゴリのいずれかと一致すると、 NotificationCompat

緊急メッセージを表示する

アプリにおいて、緊急かつ時間的制約のあるメッセージを表示する必要がある場合があります。たとえば、 着信やアラーム音などを検知できますそのような場合は、 通知と一緒に追加します。

通知が呼び出されると、 デバイスのロック ステータスを確認します。

  • ユーザーのデバイスがロックされている場合、ロック画面を覆う全画面アクティビティが表示されます。
  • ユーザーのデバイスがロックされていない場合、通知に対する応答または却下の選択肢を含む展開フォームで通知が表示されます。
で確認できます。

次のコード スニペットは、通知を 次のように指定します。

Kotlin

val fullScreenIntent = Intent(this, ImportantActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
    fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setFullScreenIntent(fullScreenPendingIntent, true)

Java

Intent fullScreenIntent = new Intent(this, ImportantActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
        fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setFullScreenIntent(fullScreenPendingIntent, true);

ロック画面の可視性を設定する

ロック画面からの通知に表示される情報の詳細度を制御するには、setVisibility() を呼び出して、次のいずれかの値を指定します。

  • VISIBILITY_PUBLIC: 通知の内容全体がロック画面に表示されます。

  • VISIBILITY_SECRET: ロック画面に通知の一部も表示されません。

  • VISIBILITY_PRIVATE: 基本情報のみ(通知のアイコンや内容など)を ロック画面に表示されます。通知のすべての内容が 示しています

VISIBILITY_PRIVATE を設定する際に、 特定の詳細を隠す通知コンテンツです。たとえば、SMS アプリ 「新しいテキストメッセージが 3 件あります」という通知が表示され、 メールの内容と送信者を非表示にします。この代替手段を提供するには 作成するには、まず、Terraform で 通常どおりNotificationCompat.Builder。次に、代替通知を追加します。 通常の通知に戻ります。 setPublicVersion()

なお、投稿するかどうかについては、ユーザーがいつでも 通知はロック画面に表示され、 アプリの通知チャンネルを管理できます

通知を更新する

通知の発行後に更新するには、 NotificationManagerCompat.notify() を再度実行し、前に使用したのと同じ ID を渡します。 おすすめします前の通知を閉じると、新しい通知が作成されます してください。

必要に応じて setOnlyAlertOnce() サウンド、バイブレーション、ビジュアルで通知が途切れないようにし、 通知 - 通知が初めて表示されたときだけ通知され、その後は通知されない あります。

通知を消去する

通知は、次のいずれかが発生するまで表示されたままになります。

  • ユーザーが通知を閉じた。
  • 通知の作成時に setAutoCancel() を呼び出した場合、ユーザーが通知をタップします。
  • 発信 cancel() 通知 ID を表示します。この方法では、実行中の 通知を受け取れます。
  • 発信 cancelAll() 以前の通知がすべて削除されます。
  • メッセージの作成時にタイムアウトを設定した場合、指定した時間が経過すると、 使用し、 setTimeoutAfter()。 必要に応じて、指定したタイムアウトの前に通知をキャンセルできます 発生します。

メッセージング アプリのおすすめの方法

通知を作成する際は、以下のベスト プラクティスを参考にしてください。 メッセージ アプリとチャットアプリなどです。

MessagingStyle を使用する

Android 7.0(API レベル 24)以降、Android では通知スタイルが メッセージ コンテンツ専用のテンプレートを使用できます。NotificationCompat.MessagingStyle クラスを使用して、会話タイトル、追加メッセージ、通知のコンテンツ ビューなど、通知に表示する複数のラベルを変更できます。

次のコード スニペットは、通知のスタイルをカスタマイズする方法を示しています。 MessagingStyle クラスを使用します。

Kotlin

val user = Person.Builder()
    .setIcon(userIcon)
    .setName(userName)
    .build()

val notification = NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("2 new messages with $sender")
    .setContentText(subject)
    .setSmallIcon(R.drawable.new_message)
    .setStyle(NotificationCompat.MessagingStyle(user)
        .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
        .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
    )
    .build()

Java

Person user = new Person.Builder()
    .setIcon(userIcon)
    .setName(userName)
    .build();

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("2 new messages with " + sender)
    .setContentText(subject)
    .setSmallIcon(R.drawable.new_message)
    .setStyle(new NotificationCompat.MessagingStyle(user)
        .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
        .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
    )
    .build();

Android 9.0(API レベル 28)以降では、 Person クラスを 通知とそのアバターの最適なレンダリング

NotificationCompat.MessagingStyle を使用する手順は次のとおりです。

  • 発信 MessagingStyle.setConversationTitle() 3 人以上のユーザーとのグループ チャットのタイトルを設定できます。良い たとえば、グループ チャットの名前にするか、 名前、会話の参加者のリストなどがあります。これがなければ、 メールは、1 対 1 の会話に属するものとして 会話内の最新のメッセージの送信者に通知されます。
  • こちらの MessagingStyle.setData() メソッドを使用して、画像などのメディア メッセージを含めることができます。パターンの MIME タイプ image/* はサポートされています。

ダイレクト返信を使用する

ダイレクト返信では、ユーザーがメッセージにインラインで返信できます。

  • ユーザーがインライン返信アクションで返信した後、 MessagingStyle.addMessage() MessagingStyle の通知を更新します。通知の撤回やキャンセルは行わないでください。 通知を受け取ります。通知をキャンセルしないと、ユーザーは複数の 通知を受け取ることができます。
  • Wear OS でインライン返信アクションを使用するには、以下を呼び出します。 Action.WearableExtender.setHintDisplayInlineAction(true)
  • addHistoricMessage() メソッドを使用して、通知に履歴メッセージを追加し、ダイレクト返信の会話にコンテキストを提供します。

スマート リプライを有効にする

  • スマート リプライを有効にするには、返信アクションで setAllowGeneratedResponses(true) を呼び出します。これにより、通知が Wear OS デバイスにブリッジされたときに、ユーザーがスマート リプライ応答を使用できるようになります。スマート リプライ モデルによって生成され、モデルによって生成されています。 NotificationCompat.MessagingStyle によって提供されるコンテキスト メッセージを生成するためのデータはインターネットにアップロードされず、 できます。

通知メタデータを追加する