小工具可偵測性

在搭載 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)
}

使用者會在小工具選擇器中或應用程式內,找到並新增小工具,因為小工具的功能最符合需求。詳情請參閱「探索與宣傳」。