小工具可偵測性

在搭載 Android 8.0 (API 級別 26) 以上版本的裝置上,如果啟動器可讓使用者建立固定捷徑,也能讓使用者將小工具固定在主畫面上。與固定捷徑類似,這些固定小工具可讓使用者存取應用程式中的特定工作,並可直接從應用程式新增至主畫面,如以下影片所示。

固定小工具的範例
圖 1 固定小工具的範例。

允許使用者固定小工具

在應用程式中,您可以要求系統將小工具固定在支援的啟動器上,步驟如下:

  1. 請務必在應用程式的資訊清單檔案中宣告小工具。

  2. 呼叫 requestPinAppWidget() 方法,如以下程式碼片段所示:

val appWidgetManager = AppWidgetManager.getInstance(context)
val myProvider = ComponentName(context, ExampleAppWidgetProvider::class.java)

if (appWidgetManager.isRequestPinAppWidgetSupported) {
    // Create the PendingIntent object only if your app needs to be notified
    // when the user chooses to pin the widget. Note that if the pinning
    // operation fails, your app isn't notified. This callback receives the ID
    // of the newly pinned widget (EXTRA_APPWIDGET_ID).
    val successCallback = PendingIntent.getBroadcast(
        /* context = */ context,
        /* requestCode = */ 0,
        /* intent = */ Intent(
            // ...
        ),
        /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
}

使用者可以透過小工具挑選器,或在應用程式中功能最相關的位置,找到並新增小工具。詳情請參閱「探索和宣傳」。