Android N 及以下版本中的推薦服務

與電視互動時,使用者通常會希望先盡量減少輸入條件,再觀看內容。對許多電視使用者而言,坐下、開啟後看電視的理想情境。要讓使用者享受喜愛的內容,至少要完成的步驟通常是他們偏好的方式。

注意:您可以使用此處所述的 API,針對在 Android 7.1 (API 級別 25) 以上版本中執行的應用程式提供建議。如要為在 Android 8.0 (API 級別 26) 以上版本中執行的應用程式提供建議,應用程式必須使用推薦管道

Android 架構會在主畫面提供建議列,協助進行最小輸入互動。首次使用裝置後,電視主畫面的第一列會顯示內容推薦。從應用程式的內容目錄提供推薦內容,有助於吸引使用者再次使用您的應用程式。

圖 1 建議資料列示例。

本課程會說明如何建立推薦內容,並提供給 Android 架構,讓使用者能輕鬆探索並欣賞您的應用程式內容。本討論將說明 Android TV GitHub 存放區中 Android Leanback 範例應用程式中的某些程式碼。

建議最佳做法

推薦功能可協助使用者快速找到喜愛的內容和應用程式。建立與使用者相關的優質推薦項目,是打造優質電視應用程式使用者體驗的重要因素。因此,您應審慎考量您向使用者推薦的內容,並妥善管理。

「建議」類型

建立建議時,您應將使用者重新連結至未完成的觀看活動,或建議該活動延伸至相關內容。以下列舉幾種應考量的具體建議:

  • 接續內容建議,方便使用者繼續觀看下一集。或者,您也可以對已暫停的電影、電視節目或 Podcast 採用接續推薦功能,讓使用者只要按幾下滑鼠,就能繼續觀看暫停的內容。
  • 新內容建議,例如使用者看完其他系列的內容時,就會獲得新一集的推薦。此外,如果應用程式可讓使用者訂閱、追蹤或追蹤內容,請根據使用者追蹤的內容清單,為未觀看的項目提供新內容推薦。
  • 根據使用者歷來觀看行為推薦的相關內容

如要進一步瞭解如何設計提供最佳使用者體驗的建議資訊卡,請參閱 Android TV 設計規格中的推薦列

重新整理推薦影片

重新整理建議時,請勿只移除再重新發布建議,因為這樣會導致建議列末端顯示建議。當內容項目 (例如電影) 播放完畢後,請從建議中 將其移除

自訂推薦內容

您可以設定使用者介面元素 (例如資訊卡的前景和背景圖片、顏色、應用程式圖示、名稱和子標題),藉此自訂推薦資訊卡以傳達品牌資訊。詳情請參閱 Android TV 設計規格中的推薦列

群組建議

您可以選擇根據推薦來源將建議分組。舉例來說,應用程式可能會提供兩組推薦內容,分別是為使用者訂閱的內容推薦,以及使用者可能不知道的新熱門內容。

建立或更新推薦資料列時,系統會分別為每個群組建議排序並排序建議。透過為您的推薦內容提供群組資訊,即可確保推薦內容不會排序至不相關的推薦內容。

使用 NotificationCompat.Builder.setGroup() 即可設定建議的群組索引鍵字串。舉例來說,如要將建議標示為含有最新熱門內容的群組,您可以呼叫 setGroup("trending")

建立推薦服務

系統會透過背景處理產生內容推薦,為了讓應用程式可以提供推薦項目,請建立服務,讓系統定期將應用程式目錄的產品資訊新增至系統的建議清單。

下列程式碼範例說明如何擴充 IntentService,以建立應用程式的推薦服務:

Kotlin

class UpdateRecommendationsService : IntentService("RecommendationService") {
    override protected fun onHandleIntent(intent: Intent) {
        Log.d(TAG, "Updating recommendation cards")
        val recommendations = VideoProvider.getMovieList()
        if (recommendations == null) return

        var count = 0

        try {
            val builder = RecommendationBuilder()
                    .setContext(applicationContext)
                    .setSmallIcon(R.drawable.videos_by_google_icon)

            for (entry in recommendations.entrySet()) {
                for (movie in entry.getValue()) {
                    Log.d(TAG, "Recommendation - " + movie.getTitle())

                    builder.setBackground(movie.getCardImageUrl())
                            .setId(count + 1)
                            .setPriority(MAX_RECOMMENDATIONS - count)
                            .setTitle(movie.getTitle())
                            .setDescription(getString(R.string.popular_header))
                            .setImage(movie.getCardImageUrl())
                            .setIntent(buildPendingIntent(movie))
                            .build()
                    if (++count >= MAX_RECOMMENDATIONS) {
                        break
                    }
                }
                if (++count >= MAX_RECOMMENDATIONS) {
                    break
                }
            }
        } catch (e: IOException) {
            Log.e(TAG, "Unable to update recommendation", e)
        }
    }

    private fun buildPendingIntent(movie: Movie): PendingIntent {
        val detailsIntent = Intent(this, DetailsActivity::class.java)
        detailsIntent.putExtra("Movie", movie)

        val stackBuilder = TaskStackBuilder.create(this)
        stackBuilder.addParentStack(DetailsActivity::class.java)
        stackBuilder.addNextIntent(detailsIntent)

        // Ensure a unique PendingIntents, otherwise all
        // recommendations end up with the same PendingIntent
        detailsIntent.setAction(movie.getId().toString())

        val intent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
        return intent
    }

    companion object {
        private val TAG = "UpdateRecommendationsService"
        private val MAX_RECOMMENDATIONS = 3
    }
}

Java

public class UpdateRecommendationsService extends IntentService {
    private static final String TAG = "UpdateRecommendationsService";
    private static final int MAX_RECOMMENDATIONS = 3;

    public UpdateRecommendationsService() {
        super("RecommendationService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "Updating recommendation cards");
        HashMap<String, List<Movie>> recommendations = VideoProvider.getMovieList();
        if (recommendations == null) return;

        int count = 0;

        try {
            RecommendationBuilder builder = new RecommendationBuilder()
                    .setContext(getApplicationContext())
                    .setSmallIcon(R.drawable.videos_by_google_icon);

            for (Map.Entry<String, List<Movie>> entry : recommendations.entrySet()) {
                for (Movie movie : entry.getValue()) {
                    Log.d(TAG, "Recommendation - " + movie.getTitle());

                    builder.setBackground(movie.getCardImageUrl())
                            .setId(count + 1)
                            .setPriority(MAX_RECOMMENDATIONS - count)
                            .setTitle(movie.getTitle())
                            .setDescription(getString(R.string.popular_header))
                            .setImage(movie.getCardImageUrl())
                            .setIntent(buildPendingIntent(movie))
                            .build();

                    if (++count >= MAX_RECOMMENDATIONS) {
                        break;
                    }
                }
                if (++count >= MAX_RECOMMENDATIONS) {
                    break;
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Unable to update recommendation", e);
        }
    }

    private PendingIntent buildPendingIntent(Movie movie) {
        Intent detailsIntent = new Intent(this, DetailsActivity.class);
        detailsIntent.putExtra("Movie", movie);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(DetailsActivity.class);
        stackBuilder.addNextIntent(detailsIntent);
        // Ensure a unique PendingIntents, otherwise all
        // recommendations end up with the same PendingIntent
        detailsIntent.setAction(Long.toString(movie.getId()));

        PendingIntent intent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        return intent;
    }
}

為了讓系統能夠辨識並執行這項服務,請使用應用程式資訊清單進行註冊。下列程式碼片段說明如何將此類別宣告為服務:

<manifest ... >
  <application ... >
    ...

    <service
            android:name="com.example.android.tvleanback.UpdateRecommendationsService"
            android:enabled="true" />
  </application>
</manifest>

建立建議

推薦服務開始執行後,必須建立建議並傳遞至 Android 架構。架構會收到建議,也就是使用特定範本且標示特定類別的 Notification 物件。

設定值

如要設定推薦資訊卡的 UI 元素值,請按照下方所述的建構工具模式建立建構工具類別。首先,您需要設定建議資訊卡元素的值。

Kotlin

class RecommendationBuilder {
    ...

    fun setTitle(title: String): RecommendationBuilder {
        this.title = title
        return this
    }

    fun setDescription(description: String): RecommendationBuilder {
        this.description = description
        return this
    }

    fun setImage(uri: String): RecommendationBuilder {
        imageUri = uri
        return this
    }

    fun setBackground(uri: String): RecommendationBuilder {
        backgroundUri = uri
        return this
    }

...

Java

public class RecommendationBuilder {
    ...

    public RecommendationBuilder setTitle(String title) {
            this.title = title;
            return this;
        }

        public RecommendationBuilder setDescription(String description) {
            this.description = description;
            return this;
        }

        public RecommendationBuilder setImage(String uri) {
            imageUri = uri;
            return this;
        }

        public RecommendationBuilder setBackground(String uri) {
            backgroundUri = uri;
            return this;
        }
...

建立通知

設定值後,您就可以建構通知,將建構工具類別的值指派給通知,並呼叫 NotificationCompat.Builder.build()

此外,請務必呼叫 setLocalOnly(),以免其他裝置顯示 NotificationCompat.BigPictureStyle 通知。

下列程式碼範例示範如何建構建議。

Kotlin

class RecommendationBuilder {
    ...

    @Throws(IOException::class)
    fun build(): Notification {
        ...

        val notification = NotificationCompat.BigPictureStyle(
        NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(description)
                .setPriority(priority)
                .setLocalOnly(true)
                .setOngoing(true)
                .setColor(context.resources.getColor(R.color.fastlane_background))
                .setCategory(Notification.CATEGORY_RECOMMENDATION)
                .setLargeIcon(image)
                .setSmallIcon(smallIcon)
                .setContentIntent(intent)
                .setExtras(extras))
                .build()

        return notification
    }
}

Java

public class RecommendationBuilder {
    ...

    public Notification build() throws IOException {
        ...

        Notification notification = new NotificationCompat.BigPictureStyle(
                new NotificationCompat.Builder(context)
                        .setContentTitle(title)
                        .setContentText(description)
                        .setPriority(priority)
                        .setLocalOnly(true)
                        .setOngoing(true)
                        .setColor(context.getResources().getColor(R.color.fastlane_background))
                        .setCategory(Notification.CATEGORY_RECOMMENDATION)
                        .setLargeIcon(image)
                        .setSmallIcon(smallIcon)
                        .setContentIntent(intent)
                        .setExtras(extras))
                .build();

        return notification;
    }
}

執行推薦服務

應用程式的推薦服務必須定期執行,才能建立目前的推薦內容。如要執行服務,請建立可以執行計時器的類別,並定期叫用服務。以下程式碼範例會擴充 BroadcastReceiver 類別,以每半小時開始定期執行推薦服務:

Kotlin

class BootupActivity : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "BootupActivity initiated")
        if (intent.action.endsWith(Intent.ACTION_BOOT_COMPLETED)) {
            scheduleRecommendationUpdate(context)
        }
    }

    private fun scheduleRecommendationUpdate(context: Context) {
        Log.d(TAG, "Scheduling recommendations update")
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val recommendationIntent = Intent(context, UpdateRecommendationsService::class.java)
        val alarmIntent = PendingIntent.getService(context, 0, recommendationIntent, 0)
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                INITIAL_DELAY,
                AlarmManager.INTERVAL_HALF_HOUR,
                alarmIntent
        )
    }

    companion object {
        private val TAG = "BootupActivity"
        private val INITIAL_DELAY:Long = 5000
    }
}

Java

public class BootupActivity extends BroadcastReceiver {
    private static final String TAG = "BootupActivity";

    private static final long INITIAL_DELAY = 5000;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "BootupActivity initiated");
        if (intent.getAction().endsWith(Intent.ACTION_BOOT_COMPLETED)) {
            scheduleRecommendationUpdate(context);
        }
    }

    private void scheduleRecommendationUpdate(Context context) {
        Log.d(TAG, "Scheduling recommendations update");

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent recommendationIntent = new Intent(context, UpdateRecommendationsService.class);
        PendingIntent alarmIntent = PendingIntent.getService(context, 0, recommendationIntent, 0);

        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                INITIAL_DELAY,
                AlarmManager.INTERVAL_HALF_HOUR,
                alarmIntent);
    }
}

BroadcastReceiver 類別的實作必須在已安裝電視的電視裝置啟動後執行。如要完成這項操作,請在應用程式資訊清單中使用意圖篩選器註冊這個類別,以便監聽裝置啟動程序的完成情況。下列程式碼範例示範如何將這項設定新增至資訊清單:

<manifest ... >
  <application ... >
    <receiver android:name="com.example.android.tvleanback.BootupActivity"
              android:enabled="true"
              android:exported="false">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
      </intent-filter>
    </receiver>
  </application>
</manifest>

重要事項:如要收到啟動完成通知,應用程式必須要求 RECEIVE_BOOT_COMPLETED 權限。詳情請見 ACTION_BOOT_COMPLETED

在推薦服務類別的 onHandleIntent() 方法中,將建議張貼至管理工具,方法如下:

Kotlin

val notification = notificationBuilder.build()
notificationManager.notify(id, notification)

Java

Notification notification = notificationBuilder.build();
notificationManager.notify(id, notification);