在搭載 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); }
相關設計指南
使用者會在小工具的功能最相關時,透過小工具挑選器或從應用程式中發現並新增您的小工具。詳情請參閱「發現與宣傳」。