Android Studio implements desktop widget (APPWidget)

foreword

Widgets are an important aspect of customizing your home screen. It allows you to see the most important application data and functions directly from the user's home screen. Users can move the widget between home screen panels, resize it, and customize the amount of information in the widget to their liking. The basic types are mainly divided into: information widgets (display some key information elements that are important to users, and track the information over time), collection widgets (specially display many elements of the same type), control widgets (specially display many elements of the same type), hybrid widgets (combine elements of different types together).

This article will use an information widget-display time on the desktop as an example to learn appwidget briefly . The example is as follows:
figure 1

step one:

Create a new NewAppWidget, the specific method is as follows:

figure 2
After adding it, you can see:
image 3
each widget must define minWidth and minHeight, indicating the minimum amount of space that should be occupied by default. Widgets typically take up width and height that exceed the specified minimums. The Android home screen provides users with a grid of free space where they can place widgets and icons. This grid may vary by device. When a widget is added, it stretches horizontally and vertically to occupy the minimum number of cells required to satisfy its minWidth and minHeight constraints. Mobile phones generally cannot exceed a 4x4 grid.

Then you can see the successfully created NewAppWidget:

package com.example.myapplication;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.widget.RemoteViews;

/**
 * Implementation of App Widget functionality.
 */
public class NewAppWidget extends AppWidgetProvider {

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}

You can see that when these broadcast events occur, the AppWidgetProvider receives the following method calls:
onUpdate() : This method is called when the user adds an app widget, so it should perform basic setup.
onEnabled(context) : If the user adds two instances of the app widget, this method will only be called the first time. Use this method to open a new database or perform other setup that only needs to be done once for all app widget instances. onDisabled
(Context) : This method is called when the last instance of the app widget has been removed from the app widget's hosting app. Use this method to clean up any work done in onEnabled(Context). There is also onReceive(Context, Intent)
not shown : this method is called for every broadcast, and is called before each of the above callback methods.

Step two:

Create an app widget layout:

In fact, when NewAppWidget is created, you can find that the new_app_widget.xml layout file has been created in res/layout, and the slightly modified code is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/Widget.MyApplication.AppWidget.Container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:theme="@style/Theme.MyApplication.AppWidgetContainer">

    <TextView
        android:id="@+id/appwidget_text"
        style="@style/Widget.MyApplication.AppWidget.InnerView"
        android:layout_width="168dp"
        android:layout_height="152dp"
        android:layout_centerInParent="true"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:background="#FFBB86FC"
        android:contentDescription="@string/appwidget_text"
        android:gravity="center"
        android:text="@string/appwidget_text"
        android:textColor="@color/white"
        android:textSize="24sp"
        android:textStyle="bold|italic" />
</RelativeLayout>

At this time, the res/xml/new_app_widget_info.xml that has been created also needs to be slightly modified, as follows:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/app_widget_description"
    android:initialKeyguardLayout="@layout/new_app_widget"
    android:initialLayout="@layout/new_app_widget"
    android:minWidth="150dp"
    android:minHeight="100dp"
    android:previewImage="@drawable/example_appwidget_preview"
    android:previewLayout="@layout/new_app_widget"
    android:resizeMode="horizontal|vertical"
    android:targetCellWidth="3"
    android:targetCellHeight="3"
    android:updatePeriodMillis="86400000"
    android:widgetCategory="home_screen" />

Step three:

At this point, the basic widget has been roughly completed, and now it is necessary to change some codes in NewAppWidget.Java, and change the code in onUpdate() to:

 public   void  onUpdate(Context context, AppWidgetManager appWidgetManager,
                           int [] appWidgetIds)
   {
       final   int  N  =  appWidgetIds.length;
       for  ( int  i  =   0 ; i  <  N; i ++ )
       {
           int  appWidgetId  =  appWidgetIds[i];
           RemoteViews views  =   new  RemoteViews(context.getPackageName(),
                   R.layout.new_app_widget);
           java.text.DateFormat df  =   new  java.text.SimpleDateFormat( " hh:mm:ss " );
           views.setTextViewText(R.id.appwidget_text,  df.format( new Date()));
           appWidgetManager.updateAppWidget(appWidgetId, views);
       }
   }

Implement the widget to display the system time

Step four:

Check configuration:

You can see that the AndroidMainifest.xml code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <receiver
            android:name=".NewAppWidget"
            android:exported="false">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/new_app_widget_info" />
        </receiver>

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

Step five:

run:

Long press the screen on the Android emulator, click Widgets, find My Application, and drag it to the main screen to display the system time, as shown in the example diagram.

Summarize:

This text is just a rough learning about appwidgets through a simple example, which cannot be refreshed every second. If you need to update widgets in real time, you need to create a service class Timeservice and modify the method call in NewAppWidget.

Reference: https://developer.android.google.cn/guide/topics/appwidgets/overview
Author: Li Meixin
Original link: https://blog.csdn.net/qq_52631411/article/details/128171263

Guess you like

Origin blog.csdn.net/fjnu_se/article/details/128173230