Detecção do widget

Em dispositivos com o Android 8.0 (nível 26 da API) e versões mais recentes, as telas de início que permitem os usuários também criam atalhos fixados permitir que eles fixem widgets na tela inicial. Assim como os atalhos fixados, esses Os widgets fixados dão aos usuários acesso a tarefas específicas no app e podem ser foi adicionado à tela inicial diretamente do app, como mostrado no vídeo a seguir.

Exemplo de layout responsivo
Figura 2. Exemplo de fixação de um widget.

Permitir que os usuários fixem um widget

No app, é possível criar uma solicitação para que o sistema fixe um widget em uma tela de início compatível realizando as seguintes etapas:

  1. Declare um widget no arquivo de manifesto do app.

  2. Chame o método requestPinAppWidget() , conforme mostrado no snippet de código a seguir:

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

Os usuários encontram e adicionam seu widget pelo seletor ou pelo seu app quando a funcionalidade do widget é mais relevante. Para mais informações, consulte Descoberta e promoção.