小工具可偵測性

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

回應式版面配置範例
圖 2. 將小工具固定顯示的範例。

允許使用者固定小工具

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

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

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

Kotlin

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)

    appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
}

Java

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName myProvider = new ComponentName(context, ExampleAppWidgetProvider.class);

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).
    PendingIntent successCallback = PendingIntent.getBroadcast(
            /* context = */ context,
            /* requestCode = */ 0,
            /* intent = */ new Intent(...),
            /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT);

    appWidgetManager.requestPinAppWidget(myProvider, null, successCallback);
}

使用者可以透過小工具挑選器探索並新增您的小工具,或是在 小工具功能。若需更多資訊,請參閲 探索與宣傳