在运行 Android 8.0(API 级别 26)或更高版本的设备上,允许用户创建固定快捷方式的启动器也允许他们将小部件固定到主屏幕上。与固定快捷方式类似,这些固定小部件使用户能够访问应用中的特定任务,并且可以从应用中直接添加到主屏幕,如下面的视频所示。
允许用户固定小部件
在您的应用中,您可以通过完成以下步骤,向系统发出请求,以将小部件固定到支持的启动器上
确保您已在应用的清单文件中声明一个小部件。
调用
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); }
相关设计指南
用户可以通过小部件选择器或在小部件功能最相关时从您的应用中发现并添加您的应用小部件。有关更多信息,请参阅发现和推广。