Uncategorized

Create a simple widget

YOU ARE READING: Create a simple widget AT Vccidata_En

App widgets are application thumbnails that can be embedded in other applications (such as the home screen) and are updated regularly. These views are called widgets in the UI, and you can publish one to an app widget provider (or widget providers). An app component that can contain other widgets is called an app widget host (or widget host). The following example shows a music widget.

Example of a music widget
Figure 1. Example of a music widget

This document describes how to publish a widget using a widget provider. For details on creating your own AppWidgetHost to host app widgets, see Creating a Widget Host.

Reading: How to create a widget that pulls website data

For information on designing your widget, see App Widgets Overview.

Widget -Components

h2>

To create a widget, you need the following basic components:

AppWidgetProviderInfo Object Describes the metadata for a widget, such as a widget. B. the layout of the widget, the update frequency and the AppWidgetProvider class. Defined in the XML on this page. AppWidgetProvider class Defines the basic methods that you can use to programmatically interface with the widget. This will give you broadcasts when the widget is updated, activated, deactivated or deleted. AppWidgetProvider is declared in the manifest and then implemented as described on this page. View Layout Defines the initial layout for the widget. Defined in XML as described on this page.

App widget processing flow
Figure 2. Processing flow for app widgets

Note: Android Studio automatically creates a set of AppWidgetProviderInfo, AppWidgetProvider and view layout files. Just select New > Widget > App Widget.

In addition to the required base components, you should implement the App Widget Configuration activity if your widget requires user configuration. This activity allows users to change widget settings (e.g. the time zone for a clock widget).

  • Starting with Android 12 (API level 31) you can choose a default configuration deploy and allow users to reconfigure the widget later. For more information, see Use widget’s default configuration and allow users to reconfigure placed widgets.
  • On Android 11 (API level 30) or lower, this activity is launched every time the user closes the widget to his home screen.

Other optional but recommended improvements include flexible widget layouts, miscellaneous improvements, advanced widgets, collection widgets, and creating a widget host.

Declare the AppWidgetProviderInfo XML

The AppWidgetProviderInfo defines the essential properties of a widget. Define the AppWidgetProviderInfo object in an XML resource file with a single element and save it in the project’s res/xml/ folder.

For example:

Widget Size Attributes

The default home screen positions widgets ts in its window based on a grid of cells that have a defined height and width. In addition, most home screens only allow widgets to take on sizes that are integer multiples of the grid cells (e.g. 2 cells horizontally x 3 cells vertically).

The widget size attributes allow you to set both a default size for Your widget and specify lower and upper limits for the size of the widget. In this context, the default size of a widget is the size the widget assumes when it is first added to the home screen.

The following table describes the attributes that relate to the Get widget resizing.

Attributes and description targetCellWidth and targetCellHeight (Android 12), minWidth and minHeight

  • Starting with Android 12, the targetCellWidth and targetCellHeight attributes specify the default size of the widget in terms of grid cells. These attributes are ignored and may be ignored in Android 11 and below if the home screen does not support a grid-based layout.
  • The minWidth and minHeight attributes specify the widget’s default size in dp.If a widget’s minimum width or height values ​​do not match the cell dimensions, the values ​​are rounded up to the nearest cell size.

Note: We recommend specifying both the targetCellWidth/targetCellHeight and minWidth/minHeight attribute sets so that your app can fall back on using minWidth and minHeight when the device of the User’s TargetCellWidth and TargetCellHeight are not supported. If supported, the targetCellWidth and targetCellHeight attributes take precedence over the minWidth and minHeight attributes. minResizeWidth and minResizeHeight Specifies the absolute minimum size of the widget. These values ​​should indicate the size below which the widget would be unreadable or otherwise unusable. Using these attributes allows the user to resize the widget to a size that may be smaller than the default widget size. The minResizeWidth attribute is ignored if it is greater than minWidth or if horizontal resizing is not enabled (see resizeMode). Likewise, the minResizeHeight attribute is ignored if it is greater than minHeight or if vertical resizing is not enabled. Introduced in Android 4.0. maxResizeWidth and maxResizeHeight Specifies the recommended maximum size of the widget. If the values ​​are not a multiple of the grid cell dimensions, they are rounded up to the nearest cell size. The maxResizeWidth attribute is ignored if it is less than minWidth or if horizontal resizing is not enabled (see resizeMode). Likewise, the maxResizeHeight attribute is ignored if it is greater than minHeight or if vertical resizing is not enabled. Introduced in Android 12. resizeMode Specifies the rules by which a widget can be resized. You can use this attribute to make homescreen widgets resizable – horizontally, vertically, or on both axes. Users long-press on a widget to reveal its resize handles, then drag the horizontal and/or vertical handles to resize it in the layout grid. Values ​​for the resizeMode attribute include horizontal, vertical, and none. To declare a widget resizable horizontally and vertically, use horizontal|vertical. Introduced in Android 3.1.

Example

To illustrate how the attributes in the preceding table affect widget size, assume the following specifications:

  • A grid cell is 30 dp wide and 50 dp high.
  • The following attribute specification is provided.

From Android 12:

We use the targetCellWidth and targetCellHeight attributes as Default widget size.

The default widget size is 2×2. The widget can be resized to 2 x 1 or to 4 x 3.

Android 11 and below:

We use the attributes “minWidth” and ” minHeight” to calculate the widget’s default size.

The default width = Math.ceil(80 / 30) = 3

See also: How to Make a TeamSpeak Server: For Linux, Windows, macOS Pointing Domain to the Server

The default height = Math.ceil(80 / 50) = 2

The size of the widget is 3×2 by default. The widget can be scaled down to 2 x 1 or expanded to full screen.

Note: The widget size calculation is more complex than the previous formula because it also includes widget borders and Spacing between grid cells.

Additional widget attributes

The following table describes the attributes that relate to properties other than widget size.

Attributes and Description updatePeriodMillis Defines how often the widget framework should request an update from the AppWidgetProvider by calling the onUpdate() callback method. This value doesn’t guarantee that the actual update will happen exactly on time, and we recommend updating as infrequently as possible—perhaps no more than once an hour to conserve battery power. For the full list of considerations for choosing an appropriate refresh period, see Optimizations for Refreshing Widget Content. initialLayout Points to the layout resource that defines the widget layout. configure Defines the activity that is started when the user adds the widget and allows him to configure widget properties. See Allowing Users to Configure Widgets. (Starting with Android 12, your app can skip the initial configuration. For more information, see Using the widget’s default configuration.) Description Specifies the description for the widget picker to display for your widget. Introduced in Android 12. previewLayout (Android 12) and previewImage (Android 11 and below)

  • Starting with Android 12, the previewLayout attribute specifies a scalable preview that you provide as an XML layout set for the widgets of standard size. Ideally, the layout xml specified as this attribute should be the same layout xml as the widget itself, with realistic defaults.
  • In Android 11 or lower, the previewImage attribute specifies a preview of what the widget will look like after the configuration, which the user sees when they select the app widget. If not specified, the user sees your application’s launch icon instead. This field corresponds to the android:previewImage attribute in the element in the AndroidManifest.xml file.

Note: We therefore recommend using both the previewImage and the previewLayout attribute to specify that your app can fall back to using previewImage if the user’s device doesn’t support previewLayout . See Backward compatibility with scalable widget previews for more details. autoAdvanceViewId Specifies the view ID of the widget subview to be automatically advanced by the widget host. Introduced in Android 3.0. widgetCategory Indicates whether your widget can be displayed on the home screen (home_screen), the lock screen (keyguard), or both. Only Android versions below 5.0 support lock screen widgets. For Android 5.0 and later, only home_screen is valid. widgetFeatures Declares features supported by the widget. For example, if you want your widget to use its default configuration when a user adds it, specify both the configuration_optional and reconfigurable flags. This bypasses starting the configuration activity after a user adds the widget. (The user can still reconfigure the widget afterwards.)

Use the AppWidgetProvider class to handle widget broadcasts

The AppWidgetProvider class handles widget broadcasts and updates the widget in response to Widget Lifecycle Events. The following sections describe how to declare AppWidgetProvider in the manifest and then implement it.

Declare the widget in the manifest

First, declare the AppWidgetProvider class in the AndroidManifest.xml file of your Application. For example:

The element requires the android:name attribute, that specifies the AppWidgetProvider used by the widget. The component should not be exported unless a separate process needs to send to your AppWidgetProvider, which is usually not the case.

The element must contain an element the android:name attribute. This attribute indicates that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only shipment that you must explicitly declare. The AppWidgetManager automatically sends all other widget broadcasts to the AppWidgetProvider as needed.

The element specifies the AppWidgetProviderInfo resource and requires the following attributes:

  • android: name: Specifies the name of the metadata. Use android.appwidget.provider to identify the data as an AppWidgetProviderInfo descriptor.
  • android:resource: Specifies the AppWidgetProviderInfo resource location.

Implement the AppWidgetProvider Class

The AppWidgetProvider class extends BroadcastReceiver as a convenient class for handling widget broadcasts. It only receives the event broadcasts relevant to the widget, e.g. B. when the widget is updated, deleted, activated and deactivated. When these broadcast events occur, the following AppWidgetProvider methods are called:

onUpdate() This is called to update the widget at intervals defined by the updatePeriodMillis attribute in AppWidgetProviderInfo. (See the table describing additional widget attributes in this document). This method is also called when the user adds the widget, so it should set the essential settings like For example, defining event handlers for View objects or starting a job to load data to be displayed in the widget. However, if you have declared a configuration activity without the configuration_optional flag, this method will not be called when the user adds the widget, but will be called for subsequent updates. It is the responsibility of the configuration activity to perform the initial update when the configuration is complete. (See Creating a widget configuration activity.) The main callback is onUpdate(). For more information, see Handling events with the onUpdate() class on this page. onAppWidgetOptionsChanged()

This is called when the widget is first placed and each time the widget is resized. Use this callback to show or hide content based on widget size ranges. Get the size ranges – and starting with Android 12, the list of possible sizes a widget instance can take – by calling getAppWidgetOptions(), which returns a bundle containing:

  • OPTION_APPWIDGET_MIN_WIDTH: Contains the lower limit for the width of a widget instance in dp units.
  • OPTION_APPWIDGET_MIN_HEIGHT: Contains the lower bound of the height of a widget instance in dp units.
  • OPTION_APPWIDGET_MAX_WIDTH: Contains the upper bound of the width of a widget in dp units instance.
  • OPTION_APPWIDGET_MAX_HEIGHT: Contains the upper limit of the height of a widget instance in dp units.
  • OPTION_APPWIDGET_SIZES: Contains the list of possible sizes (List), in dp units a widget instance can last. Introduced in Android 12.

onDeleted(Context, int[])

This is called each time a widget is deleted from the widget host.

onEnabled(Context)

This is called when an instance of the widget is first created. For example, if the user adds two instances of your widget, this will only be called the first time. If you need to open a new database or do some other setup that only needs to be done once for all widget instances, then this is a good place to do it.

onDisabled(Context)

This will be called as the last instance of your Widgets will be deleted from the widget host. Here you should clean up any work done in onEnabled(Context) such as: E.g. clearing a temporary database.

onReceive(Context, Intent)

This is called for each transmission and before each of the preceding callback methods. Normally you don’t need to implement this method because the default AppWidgetProvider implementation filters all widget broadcasts and calls the preceding methods as needed.

You need to declare your AppWidgetProvider class implementation with as the broadcast receiver – Element in the AndroidManifest. See Declaring a widget in the manifest on this page.

Handling events with the onUpdate() class

The most important AppWidgetProvider callback is onUpdate() because it is called when each Widget called is added to a host (unless you use a configuration activity without the configuration_optional flag). If your widget accepts user interaction events, you must register the event handlers in this callback. Unless your widget creates temporary files, databases, or performs other work that requires cleanup, onUpdate() might be the only callback method you need to define. For example, if you want a widget with a button that launches an activity when clicked, you could use the following implementation of AppWidgetProvider:

This AppWidgetProvider only defines the onUpdate() method to create a PendingIntent which starts an activity and attaches it to the widget’s button with setOnClickPendingIntent(int, PendingIntent). Note that it contains a loop that iterates through each entry in appWidgetIds, which is an array of IDs identifying each widget created by that provider. This way, if the user creates more than one instance of the widget, they will all be updated at the same time. However, only one updatePeriodMillis schedule is maintained for all instances of the widget. For example, if the update schedule is defined every two hours and a second instance of the widget is added one hour after the first, both will be updated in the period defined by the first and second update periods will be ignored (both will be updated every two hours, not every hour).

Note: Because AppWidgetProvider is an extension of BroadcastReceiver, your process is not guaranteed to continue running after the callback methods return (see BroadcastReceiver ). If your widget setup process can take several seconds (possibly while executing web requests) and you want your process to continue, consider launching a task with WorkManager in the onUpdate() method. Within the task, you can make your own updates to the widget without worrying about the AppWidgetProvider being closed due to an Application Not Responding (ANR) error.

See also example class ExampleAppWidgetProvider.java.

Receive Widget Broadcast Intents

See also: How to Create a Custom Page Template in a WordPress Theme

AppWidgetProvider is just a convenience class. If you want to receive the widget broadcasts directly, you can implement your own BroadcastReceiver or override the onReceive(Context,Intent) callback. You must observe the following intents:

  • ACTION_APPWIDGET_UPDATE
  • ACTION_APPWIDGET_DELETED
  • ACTION_APPWIDGET_ENABLED
  • ACTION_APPWIDGET_DISABLED
  • ACTION_APPWIDGET_OPTIONS_CHANGED

Creating a widget layout

You need to define an initial layout for your widget in XML and save it in the project’s res/layout/ directory. See the theme guidelines for details.

Creating the widget layout is easy if you are familiar with layouts. Note, however, that widget layouts are based on RemoteViews, which do not support all types of layouts or view widgets. You cannot use custom views or subclasses of the views supported by RemoteViews.

RemoteViews also supports ViewStub, a zero-sized invisible view that you can use to lazily inflate layout resources at runtime.

Support for stateful behavior

Android 12 adds new support for stateful behavior using the following existing components:

  • CheckBox

  • Switch

  • RadioButton

The widget is still stateless. Your app needs to save state and register for state change events.

Example of shopping lists -Widget with stateful behavior
Figure 3. Example of stateful behavior

Note: Always explicitly set the current enabled state Use RemoteViews.setCompoundButtonChecked or you may encounter unexpected results when your widget is dragged or resized.

The following code sample shows how these components are implemented.

Set two different layouts, one targeting devices running Android 12 or higher (res/layout-v31) and the other targeting previous Android 11 or lower (in the default res/layout folder).

Implement rounded corners

Introducing Android 12 rt the following system parameters to set the radius of the rounded corners of your widget:

  • system_app_widget_background_radius: The corner radius of the widget behind the ground, which will never be greater than 28dp.

  • system_app_widget_inner_radius: The corner radius of each view inside the widget. That’s exactly 8 dp less than the background radius to align well when using 8 dp padding.

The example below shows a widget that uses system_app_widget_background_radius for the corner of the widget and system_app_widget_inner_radius used for views inside the widget.

 Widget shows radii of widget background and views inside widget
Figure 4. Rounded corners

1 Corner of widget.

2 Corner of a view within the widget.

Important considerations about rounded corners

  • Third-party launchers and device manufacturers can use the system_app_widget_background_radius Override parameter to be less than 28dp. The system_app_widget_inner_radius parameter is always 8 dp smaller than the value of system_app_widget_background_radius.
  • If your widget doesn’t use @android:id/background or defines a background that clips its content based on the outline (with Android: clipToOutline set to true), the launcher will attempt to automatically detect the background and crop the widget using a rounded rectangle of up to 16 dp. See Make sure your widget is compatible with Android 12.

To ensure widget compatibility with previous Android versions, we recommend defining custom attributes and using a custom theme to override them for Android 12 shown in the following example XML files:

See also: Comprehensive Dreamweaver Tutorial

.

See also  How to Design Your WordPress Site with Dynamic Content

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button