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 que os usuários criem atalhos fixados também permitem fixar widgets na tela inicial. Assim como os atalhos fixados, esses widgets fixados dão aos usuários acesso a tarefas específicas no app e podem ser adicionados à tela inicial diretamente, 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, você pode criar uma solicitação para que o sistema fixe um widget em uma tela de início compatível seguindo estas etapas:

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

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

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 descobrem e adicionam seu widget pelo seletor ou pelo app quando a funcionalidade dele é mais relevante. Para mais informações, consulte Descoberta e promoção.