特定の状況では、アプリで継続的なアラームや着信などを使用して、ユーザーの注意を早急に引き付けることが必要になります。以前は、このような目的でアプリを構成するために、通常はアプリのバックグラウンド処理中にアクティビティを起動していました。
Android 10(API レベル 29)以上を実行しているデバイスで同様の動作を提供するには、このガイドで説明されている手順を実施します。
高優先度通知を作成する
通知を作成する際は、わかりやすいタイトルとメッセージを指定します。オプションとして、全画面表示インテントも使用できます。
通知の例を次のコード スニペットに示します。
Kotlin
val fullScreenIntent = Intent(this, CallActivity::class.java) val fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT) val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Incoming call") .setContentText("(919) 555-1234") .setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_CALL) // Use a full-screen intent only for the highest-priority alerts where you // have an associated activity that you would like to launch after the user // interacts with the notification. Also, if your app targets Android 10 // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in // order for the platform to invoke this notification. .setFullScreenIntent(fullScreenPendingIntent, true) val incomingCallNotification = notificationBuilder.build()
Java
Intent fullScreenIntent = new Intent(this, CallActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("Incoming call") .setContentText("(919) 555-1234") .setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_CALL) // Use a full-screen intent only for the highest-priority alerts where you // have an associated activity that you would like to launch after the user // interacts with the notification. Also, if your app targets Android 10 // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in // order for the platform to invoke this notification. .setFullScreenIntent(fullScreenPendingIntent, true); Notification incomingCallNotification = notificationBuilder.build();
通知をユーザーに表示する
ユーザーに通知が表示されたとき、ユーザーはアプリのアラートまたはリマインダーについて承認もしくは却下を選択できます。たとえば、ユーザーは電話の着信に応答するか拒否するかを選択できます。
電話の着信などの継続的な通知は、フォアグラウンド サービスに関連付けます。次のコード スニペットは、フォアグラウンド サービスに関連付けられた通知を表示する方法を示しています。
Kotlin
// Provide a unique integer for the "notificationId" of each notification. startForeground(notificationId, notification)
Java
// Provide a unique integer for the "notificationId" of each notification. startForeground(notificationId, notification);