יצירת התראה

ההתראות מספקות מידע קצר ועדכני על האירועים באפליקציה בזמן שהוא לא בשימוש. במסמך הזה מוסבר איך ליצור התראה באמצעות בתכונות שונות. למבוא לאופן שבו התראות מופיעות ב-Android: סקירה כללית על התראות לקוד לדוגמה שמשתמש בהתראות, אפשר לעיין בקטע אנשים קטע לדוגמה ב-GitHub.

הקוד בדף הזה משתמש NotificationCompat ממשקי API מספריית AndroidX. ממשקי ה-API האלה מאפשרים להוסיף תכונות שזמינות רק בגרסאות חדשות יותר של Android, ועדיין לספק תאימות ל-Android 9 (רמת API 28). אבל יש תכונות מסוימות, כמו 'תשובה בתוך השורה', יובילו לחוסר פעולה (no-op) בגרסאות קודמות.

הוספה של ספריית הליבה של AndroidX

רוב הפרויקטים שנוצרים באמצעות Android Studio כוללים את של יחסי התלות כדי להשתמש ב-NotificationCompat, מוודאים שברמת המודול הקובץ build.gradle כולל את התלות הבאה:

מגניב

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 לאובייקט. בדוגמה הבאה אפשר לראות איך ליצור התראה עם הבאים:

  • סמל קטן, מוגדר על ידי 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);

ה-constructor של 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)

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 ואילך, עליך לרשום את ערוץ ההתראות של האפליקציה עם על ידי העברת מופע של 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)
    }
}

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

כיוון שעליך ליצור את ערוץ ההתראות לפני פרסום תוכן כלשהו התראות ב-Android 8.0 ואילך, יש להריץ את הקוד הזה ברגע שהאפליקציה מופעלת מתחיל. אפשר לכנות את השם הזה שוב ושוב, כי יצירת ערוץ ההתראות לא מבצע כל פעולה.

ה-constructor של 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)

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() בדוגמה שלמעלה נשמר הניווט הצפוי של המשתמש אחרי שהם פותחים את האפליקציה באמצעות ההתראה. כדאי לבצע להשתמש בו בהתאם לסוג הפעילות שאתם מתחילים. זו יכולה להיות אחת הבאים:

  • פעילות שקיימת אך ורק לצורך תגובות להתראה. אין סיבה שהמשתמש מנווט לפעילות הזו במהלך שימוש רגיל באפליקציה, כך שהפעילות תתחיל משימה חדשה במקום להוסיף אותה לאפליקציה משימה קיימת ובחזרה מקבץ תמונות. כאן לסוג ה-Intent שנוצר בדוגמה שלמעלה.

  • פעילות שקיימת בזרימת האפליקציה הרגילה של האפליקציה. במקרה הזה, התחלת הפעילות יוצרת מקבץ אחורי כדי שהציפיות של המשתמש עבור הלחצנים 'הקודם' ו'למעלה' נשמר.

למידע נוסף על הדרכים השונות להגדרת הכוונה של ההתראה, אפשר לעיין במאמר התחלת פעילות מהתראה.

הצגת ההתראה

כדי שההתראה תופיע, צריך להתקשר NotificationManagerCompat.notify() באמצעות מזהה ייחודי של ההתראה, והתוצאה של 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(), מאחר שאתם זקוקים לה כשתרצו לעדכן או להסיר את התראה.

בנוסף, כדי לבדוק התראות בסיסיות במכשירים שפועלים ב-Android מגרסה 13 ואילך, אפשר להפעיל את ההתראות באופן ידני או ליצור תיבת דו-שיח כדי התראות של בקשות.

הוספת לחצני פעולה

התראה יכולה להציע עד שלושה לחצני פעולה שמאפשרים למשתמש להגיב במהירות, למשל כדי להעביר תזכורת למצב נודניק או להשיב להודעת טקסט. אבל אלה אסור שלחצני פעולה ישכפלו את הפעולה המבוצעת כאשר המשתמש מקיש על התראה.

איור 3. התראה עם לחצן פעולה אחד.

כדי להוסיף לחצן פעולה, צריך להעביר PendingIntent אל addAction() . הדבר דומה להגדרת פעולת ההקשה שמוגדרת כברירת מחדל בהתראה, למעט במקום להתחיל פעילות, אפשר לעשות דברים אחרים, כמו התחלת פעילות 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)</span>
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);</span>

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. מקישים על 'תשובה'. הלחצן פותח את קלט הטקסט.

פעולת המענה הישיר מופיעה כלחצן נוסף בהודעה פותח קלט טקסט. כשהמשתמש מסיים להקליד, המערכת מצרפת את הטקסט ל-Intent שציינתם לפעולת ההתראה, ושולח את את כוונת הרכישה באפליקציה.

הוספת לחצן לתשובה

כדי ליצור פעולת התראה שתומכת בתשובה ישירה, מבצעים את השלבים הבאים:

  1. יוצרים מופע של RemoteInput.Builder שאפשר להוסיף לפעולת ההתראה. ה-constructor של הכיתה מקבל מחרוזת שבה המערכת משתמשת כמפתח לקלט הטקסט. האפליקציה שלך מאוחר יותר משתמש במפתח הזה כדי לאחזר את הטקסט של הקלט.

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

המערכת מבקשת מהמשתמש להזין תגובה כשהוא מפעיל את פעולת ההתראה, כפי שמוצג באיור 4.

אחזור קלט של משתמשים מהתשובה

כדי לקבל קלט ממשתמשים מממשק המשתמש של התשובה בהתראה, צריך להתקשר RemoteInput.getResultsFromIntent() להעביר את Intent שהתקבל ב-BroadcastReceiver:

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() עם אותו מזהה ואותו תג, אם נעשה בו שימוש. הדבר נדרש כדי להסתיר את ממשק המשתמש של המענה הישיר ולאשר למשתמש שהתשובה שלו מתקבל ומעובד בצורה תקינה.

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) הפרמטר הראשון הוא המילה "complete" הוא 100. השנייה היא כמה הושלם. האפשרות האחרונה מציינת שזו התקדמות ידועה בר.

תוך כדי ביצוע הפעולה, יש להתקשר ברציפות אל setProgress(max, progress, false) עם ערך מעודכן עבור progress ולהנפיק מחדש את ההתראה, בהתאם אפשר לראות בדוגמה הבאה.

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

בסיום הפעולה, הערך של progress חייב להיות שווה ל-max. אפשר להשאיר את סרגל התקדמות כדי להראות שהפעולה הסתיימה או כדי להסיר אותה. בכל מקרה, מעדכנים את טקסט ההתראה כדי להראות שהפעולה הושלמה. כדי להסיר: בסרגל ההתקדמות, קוראים לפונקציה 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

הצגת הודעה דחופה

ייתכן שהאפליקציה תצטרך להציג הודעה דחופה ודחופה, כמו שיחת טלפון נכנסת או התראה מצלצלת. במצבים כאלה, ניתן לשייך Intent במסך מלא עם ההתראה.

כשההתראה מופעלת, המשתמשים רואים אחד מהפרטים הבאים, בהתאם סטטוס הנעילה של המכשיר:

  • אם המכשיר של המשתמש נעול, תופיע פעילות במסך מלא ותכסה את במסך הנעילה.
  • אם המכשיר של המשתמש לא נעול, ההתראה תופיע בתצוגה מורחבת שכולל אפשרויות לטיפול בהתראה או לסגירה שלה.

קטע הקוד הבא מראה איך לשייך את ההתראה אל Intent במסך מלא:

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 הודעות טקסט חדשות", אבל מסתיר את התוכן ואת השולחים של ההודעה. כדי לספק את החלופה הזו צור את ההודעה החלופית באמצעות NotificationCompat.Builder כרגיל. לאחר מכן, מצרפים את ההתראה החלופית. להתראה הרגילה עם setPublicVersion()

כדאי לזכור שלמשתמש תמיד יש שליטה מלאה ההתראות מופיעות במסך הנעילה ויכולים לשלוט בהן בהתאם ערוצי ההתראות של האפליקציה.

עדכון התראה

כדי לעדכן התראה לאחר ההנפקה, צריך להתקשר NotificationManagerCompat.notify() שוב, מועברת עם אותו המזהה שבו השתמשת. לפני. אם ההתראה הקודמת נסגרת, נוצרת התראה חדשה במקום זאת.

אפשר גם להתקשר setOnlyAlertOnce() כך שההתראה תפריע למשתמש - באמצעות צליל, רטט או תוכן חזותי רמזים - רק בפעם הראשונה שההתראה מופיעה ולא מאוחר יותר

הסרת התראה

ההתראות נשארות גלויות עד שמתקיים אחד מהתנאים הבאים:

  • המשתמש סוגר את ההתראה.
  • המשתמש יקיש על ההתראה, אם תתקשרו אל setAutoCancel() בזמן שאתם יוצרים את ההתראה.
  • שיחה 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()

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() כדי להגדיר כותרת לצ'אטים קבוצתיים עם יותר משני אנשים. טובה שם השיחה יכול להיות השם של הצ'אט הקבוצתי, או אם לא לתת שם, רשימה של כל המשתתפים בשיחה. בלי זה, ההודעה עלולה להיחשב בטעות כשייכת לשיחה אישית עם השולח של ההודעה האחרונה בשיחה.
  • משתמשים ב MessagingStyle.setData() כדי לכלול הודעות מדיה כמו תמונות. סוגי MIME של הדפוס התמונה/* נתמכים.

שימוש בתשובה ישירה

מענה ישיר מאפשר למשתמש להשיב בתוך הודעה.

  • אחרי שמשתמש משיב עם הפעולה של התשובה בגוף ההודעה, משתמשים בפונקציה MessagingStyle.addMessage() כדי לעדכן את ההתראה מ-MessagingStyle, ולא למשוך או לבטל את התראה. אם לא מבטלים את ההתראה, המשתמש יכול לשלוח מספר מודעות תשובות מההודעה.
  • כדי שפעולת התשובה בשרשור תתאים ל-Wear OS, צריך להתקשר Action.WearableExtender.setHintDisplayInlineAction(true)
  • משתמשים ב addHistoricMessage() שיטה להוספת הקשר לשיחה בתשובה ישירה על ידי הוספת הודעות להתראה.

הפעלת התכונה 'תשובה מהירה'

  • כדי להפעיל את התכונה 'תשובה מהירה', צריך להתקשר setAllowGeneratedResponses(true) על פעולת התשובה. לכן התשובות המהירות יהיו זמינות עבור משתמשים כשההתראה עוברת למכשיר Wear OS. תשובה מהירה נוצרות על ידי מודל למידת מכונה בשעון לחלוטין, את ההקשר שסופק על ידי NotificationCompat.MessagingStyle ולא מעלים נתונים לאינטרנט כדי ליצור תשובות מדויקות.

הוספת מטא-נתונים של התראה