微件可检测性

在搭载 Android 8.0(API 级别 26)及更高版本的设备上,允许用户创建固定的快捷方式的启动器也允许用户将微件固定到其主屏幕上。与固定的快捷方式类似,这些固定的微件也能让用户访问应用中的特定任务,并且可以直接从应用添加到主屏幕,如以下视频所示。

固定 widget 的示例
图 1. 固定 widget 的示例。

允许用户固定 widget

在您的应用中,您可以创建一个请求,让系统将 widget 固定到支持的启动器上,只需完成以下步骤即可:

  1. 确保您在应用的清单文件中声明了 widget

  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)
}

当微件的功能最相关时,用户可以通过微件选择器或从您的应用中发现并添加微件。如需了解详情,请参阅发现和推广