Engage SDK 程式碼實驗室

1. 簡介

上次更新時間:2025 年 5 月 14 日

什麼是 Engage SDK?

Engage SDK 可將個人化應用程式內容帶到使用者在多個裝置端 Google 途徑上的位置,進而提升應用程式的參與度。有了 Engage SDK,應用程式就能針對已安裝的使用者,提供個人化 (一對一) 推薦內容和後續內容,在還沒開啟應用程式前吸引他們的目光。

內容途徑

集合

Entertainment Space

Play 商店 (即將推出)

透過新的 Play 商店小工具,將內容直接顯示在使用者的主畫面上。

在特定 Android 平板電腦上為娛樂內容建立新的接觸點。

今年夏天起,您將可透過更多途徑存取資訊,首先是 Play 商店。

建構項目

完成本程式碼實驗室後,您將擁有一個 Android 影片應用程式,可將內容傳送至 Google 途徑。

軟硬體需求

  • 最新版 Android SDK
  • 最新版 Android Studio
  • 一台搭載 Android 10 以上版本的行動裝置。
  • USB 資料傳輸線,用於將行動裝置連接至開發電腦。

體驗

  • 您必須具備 Java 或 Kotlin 相關經驗。
  • 您必須具備 Android 開發知識。

2. 執行範例應用程式

如要開始使用,請下載範例應用程式的程式碼,以便您跟著本程式碼實驗室的說明操作。

如果已安裝 Git,請複製存放區。

git clone https://github.com/googlesamples/engage-sdk-samples.git

或者,您也可以點選這個連結下載原始碼,然後將下載的 ZIP 檔案解壓縮。

這個專案使用 Gradle 建構系統。如要建構這個專案,請使用 gradlew 建構指令,或在 Android Studio 中使用「Import Project」

下載程式碼後,您會看到兩個範例專案。

  • Java 開發人員:使用 read 範例應用程式

這個應用程式是基本圖書媒體庫。使用者可以從清單中選取書籍,然後開始閱讀。這個應用程式會示範如何發布「推薦內容」和「後續內容」資料。

  • Kotlin 開發人員:使用 watch 範例應用程式

這個應用程式是基本影片媒體庫。使用者可以從清單中選取影片,然後開始觀看影片。這個應用程式會示範如何發布「推薦內容」和「後續內容」資料。

如需更多學習 Android 開發的相關資源,請造訪 developer.android.com 的開發人員指南。

3. 建構實體

在本程式碼實驗室中,我們將分別參考 Engage SDK Read 整合指南Engage SDK Watch 整合指南,分別針對readwatch 範例應用程式進行整合。

實體:代表叢集中單一項目的物件。實體可以是電子書、電影或任何相關內容類型。

針對 read 內容,SDK 提供以下實體類型:

  • EbookEntity
  • AudiobookEntity
  • BookSeriesEntity

針對 watch 內容,SDK 提供以下實體類型:

  • MovieEntity
  • TvShowEntity
  • TvSeasonEntity
  • TvEpisodeEntity
  • LiveStreamingVideoEntity
  • VideoClipEntity

在 read 範例應用程式中,前往 EbookToEntityConverter.java 檔案,其中包含用於建構要發布的 EbookEntity 的方法。

EbookEntity.Builder entityBuilder = new EbookEntity.Builder()
        .setName("NAME OF EBOOK")
        .addAuthor("AUTHOR NAME")
        .setActionLinkUri(Uri.parse("DEEPLINK URI OF THIS EBOOK"))
        ...
         .build()

在 watch 範例應用程式中,前往 ItemToEntityConverter.kt 檔案,其中包含用於建構要發布的 MovieEntity 的方法。

val movieBuilder: MovieEntity.Builder =
      MovieEntity.Builder()
        .setName("NAME OF THE MOVIE")
        .addPosterImage(
          Image.Builder()
            .setImageUri(
              Uri.parse("android.resource://movie")
            )
            .setImageWidthInPixel(408)
            .setImageHeightInPixel(960)
            .setImageTheme(ImageTheme.IMAGE_THEME_LIGHT)
            .build()
        )
        .setPlayBackUri(Uri.parse(movie.playbackUri))
        .setReleaseDateEpochMillis(movie.releaseDate)
        .setAvailability(movie.availability)
        .setDurationMillis(movie.durationMillis)
        .addGenre(movie.genre)
          ..
           .build()

同樣地,您也可以在應用程式中將自有資料項目轉換為要發布的對應 Engage 實體。

4. 建立推薦叢集

實體建立完成後,我們可以將實體分組至叢集中。

叢集是指一組打包在一起的內容集合,這些項目可視覺化為 UI 檢視畫面,其中包含單一開發合作夥伴提供的一組內容項目。

e8ec28fa54ac7eec.png範例圖

Entertainment Space UI 顯示單一合作夥伴提供的電子書實體推薦叢集。

針對大多數類別 (包括 read 內容和 watch 內容),SDK 提供下列叢集類型:

  • 「推薦」叢集可根據使用者在應用程式中的行為提供個人化內容,並依主題 (例如新推出、價格下降或使用者喜愛的主題) 進行分類。每個應用程式最多可為每位使用者提供 5 個推薦叢集。
  • 「後續」叢集可在單一 UI 群組中,顯示多個應用程式提供的內容,協助使用者繼續觀看未看完的電影或電子書等內容。
  • 「精選」叢集可使用更大、更高級的 UI 範本,在多應用程式叢集中突顯明星型內容。

我們要為 read 和 watch 內容建立推薦叢集。

read 範例應用程式中,前往 GetRecommendationClusters.java 檔案,這個檔案會顯示建構推薦叢集的範例。

RecommendationCluster.Builder clusterBuilder = new RecommendationCluster.Builder();
// Set the cluster title
clusterBuilder.setTitle("For You");
for (int id : ebookIds) {
  //Create an ebook entity.
  EbookEntity entity = EbookToEntityConverter.convert(id); 
  // Add the ebook entity to the cluster
  clusterBuilder.addEntity(entity);
}
// Build the cluster
return clusterBuilder.build();

watch 範例應用程式中,前往 ClusterRequestFactory.kt 檔案,這個檔案會顯示建構推薦叢集的範例。

// Loads all the movie data 
val recommendationsList = movieDao.loadMovieIsCurrentlyWatching(false)
val recommendationCluster = RecommendationCluster.Builder()
for (item in recommendationsList) {
   //Create a movie entity.
    val movieEntity = ItemToEntityConverter.convertMovie(item)
    // Add the movie entity to the cluster
    recommendationCluster.addEntity(movieEntity)
}
// Build the cluster
return recommendationCluster.build

5. 發布推薦叢集

我們已瞭解如何建構實體,以及如何將這些實體分組成叢集。接下來,我們將說明如何發布叢集。

AppEngagePublishClient 用於建立連線,以發布叢集。

步驟 1:初始化用戶端。

// Java version
AppEngagePublishClient client = new AppEngagePublishClient(context);
// Kotlin version
val client = AppEngagePublishClient(context)

步驟 2:建立發布叢集的要求

在 read 範例應用程式中,查看 EngageServiceWorker.java 中的 setRecommendations 方法

// Initialize the builder
PublishRecommendationClustersRequest.Builder publishRequestBuilder = new PublishRecommendationClustersRequest.Builder();

// Add all Recommendation Clusters
for (RecommendationCluster cluster : clusters) {
   publishRequestBuilder.addRecommendationCluster(cluster);
}
// Build the request    
publishRequestBuilder.build();

在 watch 範例應用程式中,查看 ClusterRequestFactory.kt 中的 constructRecommendationClustersRequest 方法

// Initialize the builder
val request = PublishRecommendationClustersRequest.Builder()
// Add all Recommendation Cluster
.addRecommendationCluster(recommendationCluster)
// Build the request    
.build()

步驟 3:在 AppEngagePublishClient 中呼叫 publishRecommendationClusters 方法

在 read 範例應用程式中,查看 EngageServiceWorker.java 中的 setRecommendations 方法

client.publishRecommendationClusters(publishRequest);

在 watch 範例應用程式中,查看 EngageServiceWorker.kt 中的 publishRecommendations 方法

client.publishRecommendationClusters(request)

使用 isServiceAvailable API

請先呼叫 isServiceAvailable,確認是否允許發布,再呼叫 publish API。

在 read 範例應用程式中,查看 EngageServiceWorker.java 中的 startWork 方法

client.isServiceAvailable.addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Handle IPC call success
        if(task.result) {
          // Service is available on the device, proceed with content publish
          // calls.
          client.publishRecommendationClusters(request)
        } else {
          // Service is not available, do not publish.
        }
    } else {
      // The IPC call itself fails, proceed with error handling logic here,
      // such as retry.
    }
}

在 watch 範例應用程式中,查看 EngageServiceWorker.kt 中的 doWork 方法

client.isServiceAvailable.addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // Handle IPC call success
        if(task.result) {
          // Service is available on the device, proceed with content publish
          // calls.
          client.publishRecommendationClusters(request)
        } else {
          // Service is not available, do not publish.
        }
    } else {
      // The IPC call itself fails, proceed with error handling logic here,
      // such as retry.
    }
}

6. 發布狀態

建議您使用 updatePublishStatus API,指出內容未發布的理由。這樣做可協助 Google 避免在您應用程式刻意不發布內容時發出錯誤警告,引導使用者採取修正動作來存取內容,以及提供有關內容發布健康度的洞察資料。

如要瞭解狀態碼,請參閱開發人員網站。舉例來說,如果使用者需要登入才能看到內容,請使用 NOT_PUBLISHED_REQUIRES_SIGN_IN。我們會在下一個步驟中套用這段程式碼。

在 read 範例應用程式中,查看 EngageServiceWorker.kt 中的 publishAndSetResult 方法

int publishStatusCode;
              if (loggedInAccount.isPresent()) {
                // If an account is logged in and content is published
                publishStatusCode = AppEngagePublishStatusCode.PUBLISHED;
              } else {
                // If an account is not logged in and no content is published
                publishStatusCode = AppEngagePublishStatusCode.NOT_PUBLISHED_REQUIRES_SIGN_IN;
              }
              setPublishStatus(client, publishStatusCode);
            })

在 watch 範例應用程式中,查看 EngageServiceWorker.kt 中的 publishUserAccountManagement 方法

private suspend fun publishUserAccountManagement(): Result {
    val publishTask: Task<Void>
    val statusCode: Int
    if (db.accountDao().isAccountSignedIn()) {
      // If an account is logged in and content is published
statusCode = AppEngagePublishStatusCode.PUBLISHED
    } else {
     // If an account is not logged in and no content is published
      statusCode = AppEngagePublishStatusCode.NOT_PUBLISHED_REQUIRES_SIGN_IN
    }
    return publishAndProvideResult(publishTask, statusCode)
  }

7. Work Manager 和廣播意圖

Work Manager

建議您在背景執行內容發布工作 (使用 WorkManager)。定期 (例如每天) 安排廣告活動,並/或根據使用者事件 (例如應用程式開啟時或使用者完成閱讀工作階段後) 安排廣告活動。以下範例聚焦於排定的發布內容。

在 read 範例應用程式中SetEngageState.java 檔案中的 queuePeriodicSetEngageStateWorker 提供如何設定 WorkManager 的範例。

// Create a work manager
WorkManager workManager = WorkManager.getInstance(appContext);

// Set up a periodic work request for 24 hrs.
PeriodicWorkRequest publishRequest =
        new PeriodicWorkRequest.Builder(
                EngageServiceWorker.class, /* repeatInterval= */ 24, TimeUnit.HOURS)
            .setInputData(clusterToPublishData)
            .build();
// Add the work request to queue
workManager.enqueueUniquePeriodicWork(
        publishWorkName, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, publishRequest);

在 watch 範例應用程式中Publisher.kt 中的 periodicallyCallEngageServiceWorker 提供如何設定 WorkManager 的範例

// Set up a periodic work request for 24 hrs.
val workRequest = PeriodicWorkRequestBuilder<EngageServiceWorker>(
          repeatInterval = 24,
          repeatIntervalTimeUnit = TimeUnit.HOURS
        )
        .setInputData(workDataOf(PUBLISH_TYPE to publishType))
        .build()

// Create a work manager and add the work request to queue
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(
workerName,
ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE,
workRequest
)

廣播意圖

除了透過工作發出發布內容 API 呼叫,您還需要設定 BroadcastReceiver 來接收內容發布要求。

廣播意圖的目標主要用於應用程式重新啟動及強制同步處理資料。廣播意圖的傳送頻率通常不高。觸發廣播意圖的唯一時機,就是 Engage Service 判定內容可能過時 (例如已滿一週)。這樣一來,即使應用程式已有長時間未執行,使用者也能獲得最新的內容體驗。

BroadcastReceiver 必須透過下列兩種方式進行設定:

  • 使用 Context.registerReceiver() 以動態方式註冊 BroadcastReceiver 類別的例項,這樣做可讓仍在記憶體中運行的應用程式進行通訊。

開啟 read 範例應用程式中的 MainActivity.java 檔案,檢查下列項目:

private void registerReceiver() {
    BroadcastReceiver publishReceiver = new EngageServiceBroadcastReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intents.ACTION_PUBLISH_RECOMMENDATION);
    filter.addAction(Intents.ACTION_PUBLISH_FEATURED);
    filter.addAction(Intents.ACTION_PUBLISH_CONTINUATION);
    int flags = ContextCompat.RECEIVER_EXPORTED;
    ContextCompat.registerReceiver(getApplicationContext(), publishReceiver, filter, flags);
  }
  • 在 AndroidManifest.xml 檔案中使用 <receiver> 標記,以靜態方式宣告實作項目。這樣應用程式就能在未執行的狀態下接收廣播意圖,也能發布內容。

開啟 read 範例應用程式中的 AndroidManifest.xml 檔案,檢查以下內容:

<receiver
        android:name=".publish.EngageServiceBroadcastReceiver"
        android:exported="true">
      <intent-filter>
        <action android:name="com.google.android.engage.action.PUBLISH_RECOMMENDATION" />
        <action android:name="com.google.android.engage.action.PUBLISH_FEATURED" />
        <action android:name="com.google.android.engage.action.PUBLISH_CONTINUATION" />
             </intent-filter>
 </receiver>

服務會傳送下列意圖

  • com.google.android.engage.action.PUBLISH_RECOMMENDATION:建議在收到此意圖時啟動 publishRecommendationClusters 呼叫。
  • com.google.android.engage.action.PUBLISH_FEATURED:建議在收到此意圖時啟動 publishFeaturedCluster 呼叫。
  • com.google.android.engage.action.PUBLISH_CONTINUATION:建議在收到此意圖時啟動 publishContinuationCluster 呼叫。

8. 使用驗證應用程式進行測試

下載並使用驗證應用程式驗證整合作業

驗證應用程式應將每個叢集顯示為獨立的一列。

  • 輸入要發布資料的套件名稱。

d1ad850cd02991d.png

  • 確認叢集中的所有實體皆已發布。

3953d00488212411.png

  • 確認實體中的所有欄位皆已發布。開發人員可以點選資料列中每個項目的代表圖片來驗證意圖。

23cd19224397adf3.png

驗證廣播意圖流程

如要使用驗證應用程式驗證廣播意圖,請按一下使用者介面頂端的按鈕,觸發傳送廣播的邏輯。

9cb0b5315057fbe1.png

9. 恭喜

您現在已瞭解如何在 Android 應用程式中加入 Engage SDK。

詳情請參閱 Engage SDK 開發人員指南和商家網站。

資源

根據要發布的內容類型,SDK 會包含不同類型的實體類別。您可以在下方列出的各產業整合指南中,查看可用的實體清單: