透過 Messaging and People API,將即時通訊相關功能加入 Android 應用程式

1. 事前準備

訊息應用程式製作方式相當困難。整體使用者體驗屬於主觀判斷,Android 提供 Messaging API 和 People API,改善和簡化即時通訊體驗。

在這個程式碼研究室中,您將瞭解如何使用這些 API 為 Android 上的即時通訊應用程式打造具有吸引力的生態系統。您擴充了 JetChat 應用程式,這是一款使用 Jetpack Compose 的裸機和非功能即時通訊應用程式。

必要條件

  • 對 Android 開發作業有基本瞭解
  • 通知的基本知識

建構項目

可執行下列操作的擴充 JetChat 應用程式:

  • 顯示通知,代表通知導覽匣的保留對話部分中的對話。
  • 在這些通知中提及共用目標,讓您參與應用程式對話。
  • 強制執行建立這些物件的最佳做法,以利用系統強化應用程式提供的預設體驗。

課程內容

  • 如何在通知導覽匣的保留對話部分中顯示對話相關的通知。
  • 如何瞭解 Messaging and People API 帶來的各種體驗。

軟硬體需求

  • Git
  • Android Studio
  • GitHub 帳戶

2. 做好準備

起點是以 JetChat 應用程式為基礎。範例程式碼會擴充 JetChat 應用程式,以更有效的方式展示 Messaging API 和 People API。

取得範例程式碼

如要取得本程式碼研究室的範例程式碼,請按照下列步驟操作:

  1. 從指令列複製以下 GitHub 存放區:
git clone –branch starter-code \
https://github.com/android/people-messaging-codelab.git
  1. 在 Android Studio 中開啟專案,然後按一下 a1bbb9d97659a043.png「Run app」。系統會隨即顯示「Emulator」窗格,並顯示應用程式。

探索 JetChat 擴充應用程式

  1. 在應用程式的「訊息 #composers」文字方塊中輸入訊息,然後輕觸「傳送」
  2. 離開應用程式。幾秒後,您會收到推播通知,其中包含即時通訊中某位參與者的回覆。

3. 建立對話通知

Android 11 導入了 API,可讓即時通訊相關通知顯示在通知導覽匣中的指定部分 (這是僅供對話使用)。

從狀態列向下滑動時會出現的通知導覽匣

通知必須屬於 Notification.MessagingStyle 類別,並參照長效 共用捷徑。本節將說明如何滿足這些 API 規定,以便在對話專區中顯示代表對話的通知。

如要接收 NotificationCompat.MessagingStyle 課程的通知,請按照下列步驟操作:

  1. 在 Android Studio 的「Project」分頁中,按一下 app >java >com.example.compose.jetchat >conversation,然後按兩下ConversationFragment
  2. ConversationFragment.kt 檔案中找出 ConversationFragment 類別,然後找出建立通知的 createNotification 函式 Notification 程式碼區塊。
  3. setContentText 方法替換為 setStyle 方法,將通知的樣式設為 NotificationCompat.MessagingStyle 類別。此輔助類別會新增使用 setContextText 方法設定的訊息,並提供與訊息相關的其他背景資訊,例如傳送時間和傳送者。

ConversationFragment.kt

private fun createNotification(
   notificationId: Int,
   message: Message,
   person: Person,
   shortcut: ShortcutInfoCompat,
   time: Long
): Notification? {
    ...
    .setStyle(NotificationCompat.MessagingStyle(person).addMessage(
                      NotificationCompat.MessagingStyle.Message(
                          message.content,
                          time,
                          person
                      )
    )
    )
    ...
    .build()
}

執行應用程式

  1. 執行應用程式。
  2. 在應用程式的「訊息 #composers」文字方塊中輸入訊息,然後輕觸「傳送」
  3. 離開應用程式。您又收到了推播通知,但樣式改變。包括訊息的顯示圖片和獨特風格。不過,在通知顯示位置之前,還需要完成一些步驟。

4. 建立對話的共用目標

您必須參照通知中的共用捷徑或分享目標。共用目標是在 shortcuts.xml 檔案中定義,也是處理以程式輔助方式定義的捷徑的進入點。您建立的捷徑代表應用程式中的對話,可讓您在對話中分享內容。

定義共用目標

  1. 在「專案」「專案」分頁中,以滑鼠右鍵按一下res目錄,然後選取新增 >Directory
  2. 在文字方塊中,輸入 xml,然後按下 Enter 鍵 (macOS 為 return)。
  3. xml 目錄上按一下滑鼠右鍵,然後選取「File」
  4. 在文字方塊中,輸入 shortcuts.xml,然後按下 Enter 鍵 (macOS 為 return)。
  5. shortcuts.xml 檔案中,宣告用於處理 text/plain 類型資料共用的共用目標

shortcuts.xml

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
  <share-target android:targetClass="com.example.compose.jetchat.NavActivity">
   <data android:mimeType="text/plain" />
   <category android:name="com.example.compose.jetchat.share.TEXT_SHARE_TARGET" />
 </share-target>
</shortcuts>
  1. 在「Project」分頁中,按一下「manifests,然後按兩下「AndroidManifest.xml
  2. AndroidManifest.xml 檔案中定義 shortcuts.xml 檔案:

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.compose.jetchat">

   <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Jetchat.NoActionBar">
...
 <meta-data android:name="android.app.shortcuts"
            android:resource="@xml/shortcuts" />

    </application>
</manifest>
  1. AndroidManifest.xml 檔案的 activity 元件中,定義包含共用邏輯的意圖篩選器:

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.compose.jetchat">

   ...
       <activity
           ...
           <intent-filter>
               <action android:name="android.intent.action.SEND" />
               <category android:name="android.intent.category.DEFAULT" />
               <data android:mimeType="text/plain" />
           </intent-filter>
...

定義捷徑

你必須為每則通知與相關的捷徑建立關聯。每個對話只能定義一個專屬捷徑,因為專屬捷徑代表一位聯絡人的分享對象。

如要產生捷徑,請按照下列步驟操作:

  1. 在「Project」分頁中,按一下「app>java >com.example.compose.jetchat >conversation>util,然後按兩下ConversationUtil
  2. ConversationUtil.kt 檔案中,新增 generateShortcut 函式:

ConversationUtil.kt

import android.content.Intent
import androidx.core.content.pm.ShortcutInfoCompat
import com.example.compose.jetchat.NavActivity

class ConversationUtil {

   companion object {
...
fun generateShortcut(context: Context, shortcutId: String): ShortcutInfoCompat {
   return ShortcutInfoCompat.Builder(context, shortcutId)
   .setCategories(setOf(CATEGORY_SHARE))
   .setLongLived(true)
   .setShortLabel(shortcutId)
   .setLongLabel(shortcutId)
   .setIntent(
       Intent(context, NavActivity::class.java)
           .setAction(Intent.ACTION_VIEW)
   )
   .build()
}

這個函式包含對話所需的 setPersonsetLongLived 方法。此人是與捷徑相關聯的聯絡人,並將長效設為 true 值,可確保系統快取這個捷徑,並顯示在 UI 的不同介面上。

參照通知中的捷徑

你必須參照通知中的共用捷徑。不過,你必須建立捷徑,才能推送通知。

步驟如下:

  1. ConversationFragment.kt 檔案中,找到 ConversationFragment 類別。
  2. 在呼叫 notification 變數之前,請先建立 shortcut 變數,藉此參照從 ConversationUtil.generateShortcut 產生的捷徑。
  3. notification 變數的 createNotification 方法中,將 null 替換為 shortcut 變數做為參數。

ConversationFragment.kt

private fun simulateResponseAsANotification() {
   ...
   if (message.author != "me") {
       ...
       val shortcut = ConversationUtil.generateShortcut(context!!, message.author)
       val notification = createNotification(notificationId, message, person, shortcut, time)
       ...
   }
}
  1. createNotification 方法中新增 NotificationCompat.Builder#setShortcutInfo 方法,然後傳入 shortcut 變數做為參數。

ConversationFragment.kt

private fun createNotification(
  notificatoinIf: Int,
  messagin: Message,
  person: Person,
  shortcut: ShortcutInfoCompat?,
  time: Long
): Notification {
...
return NotificationCompat.Builder(context!!,  ConversationUtil.CHANNEL_MESSAGES)
   ...
   .setShortcutInfo(shortcut)
   .build()
}

發布捷徑

  • 如要發布捷徑,請在 notificationManager.notify 方法之前的 simulateResponseAsANotification 函式中呼叫 pushDynamicShortcut 方法:

ConversationFragment.kt

import androidx.core.content.pm.ShortcutManagerCompat

...private fun simulateResponseAsANotification() {
   ...
   if (message.author != "me") {
       ...
       ShortcutManagerCompat.pushDynamicShortcut(context!!, shortcut)
       ...
   }
}

執行應用程式

  1. 執行應用程式。
  2. 在應用程式的「訊息 #composers」文字方塊中輸入訊息,然後輕觸「傳送」
  3. 離開應用程式。您又收到了一則推播通知,但其樣式更顯像對話相關的通知。顯示圖片圖示更醒目,也整合了應用程式圖示。寄件者、時間和文字訊息也變得更精簡了。

5. 選用:啟用對話框

對話框是在 Android 9 中導入,並針對 Android 11 的對話進行改善及重新利用。對話框是圓形的重疊元素,是顯示在對話中的顯示圖片。這類對話會顯示在應用程式啟動器中,方便你透過展開式泡泡回覆對話。即使已導入對話框,但使用者仍可自行選用。

如要啟用對話框,請按照下列步驟操作:

  1. AndroidManifest.xml 檔案中新增 allowEmbeddedresizeableActivity 屬性,然後將每個屬性設為 true 值:

AndroidManifest.xml

<activity
  ...
  android:allowEmbedded="true"
  android:resizeableActivity="true"
  ...
</activity>
  1. ConversationUtil.kt 檔案的 ConversationUtil 類別中,新增對話框中繼資料:

ConversationUtil.kt

import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat


fun createBubbleMetadata(context: Context, icon: IconCompat): NotificationCompat.BubbleMetadata {
        // Create bubble intent
        val target = Intent(context, NavActivity::class.java)
        val bubbleIntent = PendingIntent.getActivity(context, REQUEST_BUBBLE, target, flagUpdateCurrent(mutable = true))

        // Create bubble metadata
        return NotificationCompat.BubbleMetadata.Builder(bubbleIntent, icon)
            .setDesiredHeight(400)
            .setSuppressNotification(true)
            .build()
    }
  1. ConversationFragment.kt 檔案中,建立並參照通知上的對話框中繼資料:

ConversationFragment.kt

private fun createNotification(
  notificatoinIf: Int,
  messagin: Message,
  person: Person,
  shortcut: ShortcutInfoCompat?,
  time: Long
): Notification {
...
// Reference the bubble metadata in the notification.
  return NotificationCompat.Builder(context!!,     ConversationUtil.CHANNEL_MESSAGES)
    ...
     .setBubbleMetadata(ConversationUtil.createBubbleMetadata(context!!, person.icon!!))
...
    .build()
}

執行應用程式

  1. 執行應用程式。
  2. 在應用程式的「訊息 #composers」文字方塊中輸入訊息,然後輕觸「傳送」
  3. 離開應用程式。幾秒後,你會收到以對話框形式顯示的通知訊息。
  4. 輕觸泡泡。對話會以對話框開啟。

對話泡泡

6. 選用:分享連結

您已宣告分享目標,並在通知中參照這些目標,而 Sharesheet 會在傳送 ACTION 意圖時顯示的下半部元件,並在 Sharesheet 中顯示聯絡人。共用目標會顯示在 Sharesheet 的頂端,方便您在對話中分享多媒體內容。

如要叫用 Sharesheet,請按照下列步驟操作:

  1. 在裝置上開啟 Google Chrome,然後前往您選擇的網頁,例如 developer.android.com
  2. 如有需要,請按一下 2fdbaccda71bc5f0.png「更多端點」
  3. 按一下「分享」圖示 771b0be21764f6b6.png。Sharesheet 會顯示在畫面底部。

Sharesheet

  1. 請盡可能按一下「468248e6b8a84bb3.pngJetChat」JetChat。系統會在即時通訊中分享網址。
  2. 如果找不到 468248e6b8a84bb3.png「JetChat」JetChat,請按一下 145399af71577431.png「更多」JetChat叫用系統 Sharesheet,然後在 ShareSheet 中向上滑動並按一下 468248e6b8a84bb3.pngJetChat「JetChat」。網址會在即時通訊中分享。

這只是一個簡單的範例。可以分享更豐富的內容類型。詳情請參閱從其他應用程式擷取簡單資料

7. 恭喜

恭喜!現在您已經瞭解如何使用 Messaging and People API,為 Android 應用程式新增即時通訊相關功能。祝您聯絡愉快!

瞭解詳情