알림 만들기

알림은 앱 이벤트에 관한 짧고 시기적절한 정보를 그것은 사용 중이 아닙니다. 이 문서에서는 다양한 기능을 제공합니다 Android에서 알림이 표시되는 방식에 관한 소개는 알림 개요를 참조하세요. 알림을 사용하는 샘플 코드는 GitHub의 사용자 샘플을 참고하세요.

이 페이지의 코드는 NotificationCompat 드림 API를 가져올 수 있습니다. 이 API를 사용하면 Android와의 호환성은 계속 제공하면서 최신 버전의 Android에서 9 (API 수준 28). 하지만 인라인 답장 작업과 같은 일부 기능은 이전 버전에서는 작동하지 않습니다.

AndroidX Core 라이브러리 추가

Android 스튜디오로 만든 대부분의 프로젝트에는 종속 항목이 NotificationCompat를 사용하도록 하려면 모듈 수준의 build.gradle 파일에는 다음 종속 항목이 포함되어 있습니다.

Groovy

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

Kotlin

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

기본 알림 만들기

가장 기본적이고 간단한 형태(축소된 형태라고도 함)의 알림에는 아이콘, 제목, 소량의 텍스트 콘텐츠가 표시됩니다. 이 섹션에서는 사용자가 탭하여 앱을 실행할 수 있는 알림을 만드는 방법을 보여줍니다. 파악할 수 있습니다.

그림 1. 다음이 포함된 알림 아이콘, 제목 및 텍스트가 있습니다.

알림의 각 부분에 대한 자세한 내용은 알림을 참조하세요. 구조를 참조하세요.

런타임 권한 선언

Android 13 (API 수준 33) 이상에서는 게시를 위한 런타임 권한을 지원합니다. 비 예외 (포그라운드 서비스 (FGS) 포함) 알림을 전송합니다.

앱의 매니페스트 파일에서 선언해야 하는 권한은 다음과 같은 코드 스니펫으로 표시됩니다.

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

런타임 권한에 대한 자세한 내용은 다음을 참조하세요. 알림 런타임 권한.

알림 콘텐츠 설정

시작하려면 NotificationCompat.Builder 객체를 사용하여 알림 콘텐츠와 채널을 설정합니다. 다음 예는 있습니다.

  • 작은 아이콘, set: setSmallIcon() 사용자가 볼 수 있는 유일한 필수 콘텐츠입니다.

  • 제목(설정 주체) setContentTitle()

  • 다음으로 설정한 본문 텍스트: setContentText()

  • 알림 우선순위는 setPriority() 우선순위는 Android 7.1 및 Android 7.0에서 알림이 얼마나 살펴봤습니다 Android 8.0 이상에서는 대신 채널 중요도를 다음 섹션에 나와 있습니다.

Kotlin

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

자바

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

NotificationCompat.Builder 생성자의 경우 채널 ID를 제공해야 합니다. 이는 Android 8.0 (API 수준 26) 및 하지만 이전 버전에서는 무시됩니다.

기본적으로 알림의 텍스트 콘텐츠는 한 줄에 맞춰 잘립니다. 나 확장 알림을 만들어 추가 정보를 표시할 수 있습니다.

그림 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)

자바

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 이상에서 알림을 전송하기 전에 앱의 알림 채널을 인스턴스의 인스턴스를 전달하여 NotificationChannel~ createNotificationChannel() 다음 코드는 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)
    }
}

자바

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 클래스의 상수 중 하나를 사용합니다. 이 매개변수는 관련 알림에 대해 사용자를 중단하는 방법을 결정합니다. 이 채널에 초대합니다. Android 7.1을 지원하도록 setPriority()우선순위 설정 이전 예에서 볼 수 있듯이

알림의 중요도나 우선순위를 시스템은 사용자가 받는 경보 동작을 보장하지 않습니다. 포함 경우에 따라 시스템에서 다른 요인에 따라 중요도 수준을 변경할 수 있습니다. 사용자는 언제든지 채널을 구독합니다.

각 수준의 의미에 대한 자세한 내용은 알림 중요도 등급을 참조하세요.

알림의 탭 작업 설정

모든 알림은 일반적으로 탭에서 활동을 열려면 탭에 응답해야 합니다. 표시됩니다. 이렇게 하려면 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)

자바

// 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())
}

자바

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를 저장합니다. Gmail을 업데이트하거나 삭제하려는 경우에 필요하기 때문에 알림을 참고하세요.

또한 Android 13 이상에서는 알림을 수동으로 사용 설정하거나 알림을 요청합니다.

작업 버튼 추가

알림에서 사용자가 응답할 수 있는 최대 세 개의 작업 버튼을 제공할 수 있습니다. 알림을 일시 중지하거나 문자 메시지에 답장하는 등의 작업을 신속하게 수행할 수 있습니다. 하지만 이러한 작업 버튼은 사용자가 알림을 받을 수 있습니다.

그림 3. 작업 버튼이 하나 있는 알림

작업 버튼을 추가하려면 PendingIntentaddAction() 메서드를 사용하여 축소하도록 요청합니다. 이는 알림의 기본 탭 작업을 설정하는 것과 같습니다. 단, 활동을 실행하는 대신 백그라운드에서 작업을 실행하는 BroadcastReceiver를 시작하는 것과 같이 다른 작업을 할 수 있으므로 작업을 실행해도 이미 열려 있는 앱이 중단되지 않습니다.

예를 들어 다음 코드는 특정 수신자:

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)

자바


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()
      }
      

    자바

      // 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)
      

    자바

      // 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()
      

    자바

      // 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)
      }
      

    자바

      // 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)
}

자바

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

텍스트를 처리한 후 동일한 ID와 태그(사용된 경우)로 NotificationManagerCompat.notify()를 호출하여 알림을 업데이트합니다. 이는 바로 답장 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)
}

자바

// 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과 같이 계산됩니다. 두 번째는 얼마나 완료되었는지 알 수 있습니다. 마지막은 확정적인 진행 상황임을 나타냅니다. 있습니다.

작업이 진행됨에 따라 업데이트된 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())
}

자바

...
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)

자바

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)

자바

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개의 새로운 문자 메시지가 있습니다.'라는 알림이 표시될 수 있습니다. 그러나 메일 내용과 발신자를 숨깁니다. 이러한 대안을 먼저 대체 알림을 만듭니다. 평소와 같이 NotificationCompat.Builder합니다. 그런 다음 대체 알림을 첨부합니다. 일반 알림에 setPublicVersion()

사용자는 항상 알림은 잠금 화면에 표시되며 앱의 알림 채널에도 적용됩니다.

알림 업데이트

알림 발행 후 업데이트하려면 다음을 호출합니다. NotificationManagerCompat.notify()를 다시 한번 호출하여 사용한 것과 동일한 ID를 전달합니다. 있습니다. 이전 알림을 닫으면 새 알림이 생성됩니다. 하세요.

알림이 나중에 업데이트될 때가 아니라 처음으로 표시될 때만 알림음, 진동 또는 시각적 실마리로 사용자를 방해하도록 setOnlyAlertOnce()를 호출할 수도 있습니다.

알림 삭제

알림은 다음 중 한 가지가 발생할 때까지 계속 표시된 상태로 유지됩니다.

  • 사용자가 앱을 닫습니다.
  • 개발자가 setAutoCancel()를 호출할 때 사용자가 알림을 탭합니다. 알림을 생성합니다.
  • 특정 알림 ID에 cancel()를 호출합니다. 이 메서드는 진행 중인 있습니다.
  • 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()

자바

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() 드림 을 사용하세요. 그룹 채팅의 이름이 좋은 대화 제목이며 채팅 이름이 없는 경우 대화 참가자 목록이 좋은 대화 제목입니다. 이것이 없으면 메일이 대화에서 가장 최근 메일의 발신자입니다.
  • MessagingStyle.setData() 메서드를 사용하여 이미지와 같은 미디어 메시지를 포함합니다. 패턴의 MIME 유형입니다. image/* 만 지원됩니다.

바로 답장 사용

바로 답장을 사용하면 사용자가 메일에 인라인으로 답장할 수 있습니다.

  • 사용자가 인라인 답장 작업으로 답장한 후에는 다음을 사용합니다. MessagingStyle.addMessage() 드림 하여 MessagingStyle 알림을 업데이트하고, 있습니다. 알림을 취소하지 않으면 사용자가 알림에서 여러 개의 답장을 보낼 수 있습니다.
  • 인라인 답장 작업이 Wear OS와 호환되도록 하려면 Action.WearableExtender.setHintDisplayInlineAction(true)를 호출합니다.
  • 사용 addHistoricMessage() 드림 메서드를 추가하여 현재 검색 기록을 추가하여 바로 답장 대화에 컨텍스트를 제공할 수 있습니다. 알림을 전송합니다.

스마트 답장 사용 설정

  • 스마트 답장을 사용 설정하려면 답장 작업에서 setAllowGeneratedResponses(true)를 호출합니다. 이렇게 하면 다음 사용자가 스마트 답장 응답을 사용할 수 있습니다. 사용자에게 알림을 전송합니다. 스마트 답장 머신러닝 모델에 의해 응답이 NotificationCompat.MessagingStyle에서 제공하는 컨텍스트 인터넷에 업로드되지 않으며 확인할 수 있습니다

알림 메타데이터 추가