Rilevabilità del widget

Sui dispositivi con Android 8.0 (livello API 26) e versioni successive, i launcher che consentono agli utenti di creare scorciatoie aggiunte alla schermata Home consentono anche di aggiungere widget alla schermata Home. Analogamente alle scorciatoie aggiunte, questi widget aggiunti consentono agli utenti di accedere a attività specifiche nella tua app e possono essere aggiunti alla schermata Home direttamente dall'app, come mostrato nel video seguente.

Esempio di layout adattabile
Figura 2. Esempio di aggiunta di un widget.

Consentire agli utenti di aggiungere un widget

Nella tua app, puoi creare una richiesta al sistema per aggiungere un widget a un launcher supportato completando i seguenti passaggi:

  1. Assicurati di dichiarare un widget nel file manifest dell'app.

  2. Chiama il requestPinAppWidget() metodo, come mostrato nel seguente snippet di codice:

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

Gli utenti scoprono e aggiungono il tuo widget tramite il selettore di widget o dall'interno della tua app quando la funzionalità del widget è più pertinente. Per saperne di più, consulta Scoperta e promozione.