Android widget app Widgets

Source: Internet
Author: User

APP widget app Widgets

Application widgets are tiny application views that can be embedded into other applications (such as desktops) and receive periodic updates. You can use an app widget provider to publish a widget. The application component that can hold other app widgets is called the app widget host. The screenshot below shows a music app widget.


This article describes how to use the app widget provider to publish an app widget.

 

Basic knowledge the basics

To create an app widget, you need the following:

Appwidgetproviderinfo object

Describe the metadata of an app widget, such as the layout, update frequency, and appwidgetprovider class of the app widget. This should be defined in XML.

Implementation of the appwidgetprovider class

Define basic methods to allow you to program and connect to app widgets, which is based on broadcast events. When the app widget is updated, enabled, disabled, or deleted, you will receive broadcast notifications.

View Layout

Define the initial layout for this app widget in XML.

In addition, you can implement an app widget configuration activity. This is an optional activity. When you add an app widget, it is loaded and allowed to modify the settings of the app widget during creation.

 

The following sections describe how to create these components:

Declare An application widget in the list

First, declare the appwidgetprovider class in the androidmanifest. xml file of the application, for example:

<receiver android: name = "ExampleAppWidgetProvider">
    <intent-filter>
        <action android: name = "android.appwidget.action.APPWIDGET_UPDATE" />
    </ intent-filter>
    <meta-data android: name = "android.appwidget.provider"
               android: resource = "@ xml / example_appwidget_info" />
</ receiver>
The <receiver> element requires the android: name attribute, which specifies the AppWidgetProvider used by App Widget.

The <intent-filter> element must include an <action> element with the android: name attribute. This element specifies that AppWidgetProvider accepts ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast you must explicitly declare. When needed, AppWidgetManager will automatically send all other apps
Widget broadcast to AppWidgetProvider.

The <meta-data> element specifies the AppWidgetProviderInfo resource and requires the following attributes:

· Android: name – specifies the metadata name.

· Android: resource – specifies the AppWidgetProviderInfo resource path.

 

Add AppWidgetProviderInfo metadata

AppWidgetProviderInfo defines the basic characteristics of an App Widget, such as the minimum layout size, initial layout resources, refresh frequency, and (optional) a configuration activity that is loaded at creation time. Use a separate <appwidget-provider> element to define the AppWidgetProviderInfo object in the XML resource and save it to the res / xml / directory of the project.

such as:

<receiver android: name = "ExampleAppWidgetProvider">
    <intent-filter>
        <action android: name = "android.appwidget.action.APPWIDGET_UPDATE" />
    </ intent-filter>
    <meta-data android: name = "android.appwidget.provider"
               android: resource = "@ xml / example_appwidget_info" />
</ receiver>
The following is a summary of the <appwidget-provider> attribute:

· The values of the minWidth and minHeight properties specify the minimum area required by the App Widget layout.

The desktop position of the default App Widgets window is based on a grid of cells with exact height and width. If the minimum length and width of the App Widget does not match the size of these grid cells, then the App Widget will shrink to the closest cell size. (See App Widget Design Guidelines for more information on the size of desktop units)

Because the direction of the desktop layout (and thus the size of the unit) can vary, you should assume that the worst-case unit size is 74 pixels high and wide according to the thumb rule. However, you must subtract 2 from the final size to account for any integer rounding errors generated during pixel calculation. To find the minimum width and height independent of pixel density, use this formula:
(number of cells * 74)-2
Following this formula, you should use 72dp for each cell height and 294dp for four cell widths.

· The updatePerdiodMillis property defines how often the App Widget framework calls the onUpdate () method to request an update from the AppWidgetProvider. The actual update time is not so accurate, and we recommend that the lower the update frequency, the better-perhaps no more than once per hour to save power. You may also allow users to adjust this frequency in the configuration-some people may want to quote the stock every 15 minutes, or only four times a day.

· The initialLayout attribute points to the resource that defines the layout of the App Widget.

· The configure attribute defines the Activity, which is started when a user adds an App Widget to configure App Widget features for him or her. This is optional (read Creating below
an App Widget Configuration Activity).

See the AppWidgetProviderInfo class for more attribute information that can be accepted by the <appwidget-provider> element.

Create App Widget layout
You must define an initial layout for your App Widget in XML and save it to the project's res / layout / directory. You can use the view objects listed below to design your App Widget, but before that, please read and understand the App Widget Design Guidelines.

If you are familiar with declaring layouts in XML, then creating this App Widget layout is very simple. However, you must realize that the App Widget layout is based on RemoteViews, which does not support all types of layouts or view widgets.

A RemoteViews object (and, correspondingly, an App Widget) can support this layout class:

· FrameLayout

· LinearLayout

· RelativeLayout

And the following widget class:

· AnalogClock

· Button

· Chronometer

· ImageButton

· ImageView

· ProgressBar

· TextView

Derivation of these classes is not supported.

Use AppWidgetProvider class

You must declare your AppWidgetProvider class as a broadcast receiver by using the <receiver> element in the manifest file (see Declaring an App Widget in the Manifest above).

The AppWidgetProvider class extends BroadcastReceiver as a convenient class to handle App Widget broadcasting. AppWidgetProvider only receives event broadcasts related to this App Widget. For example, this App Widget is updated, deleted, enabled, and disabled. When these broadcast events occur, AppWidgetProvider will receive the following method call:

onUpdate (Context, AppWidgetManager, int [])

This method is called to update App Widgets at intervals. The interval is defined by the updatePeriodMillis attribute in AppWidgetProviderInfo (see Add AppWidgetProviderInfo Metadata). This method is also called when the user adds the App Widget, so it should perform basic settings, such as defining an event handler for the view and starting a temporary service Service, if needed. However, if you have already declared a configuration activity, this method adds the app to the user
Widget will not be called, but will only be called in subsequent updates. Configuration activities should be responsible for performing the first update when configuration is complete. (See Creating an App Widget Configuration Activity below.)

onDeleted (Context, int [])

App Widget is called when it is deleted from the host.

onEnabled (Context)

Called when an App Widget instance is first created. For example, if the user adds two instances of your App Widget, it will only be called the first time. If you need to open a new database or perform other settings that only need to happen once for all App Widget instances, then this is a good place to complete the job.

onDisabled (Context)

Called when the last instance of your App Widget is deleted from the host. You should do some cleanup in onEnabled (Context), such as deleting a temporary database.

onReceive (Context, Intent)

This will be called when each broadcast is received, and before the callback function above. You usually don't need to implement this method because the default AppWidgetProvider implementation filters all App Widget broadcasts and calls the above methods appropriately.

Note: In Android 1.5, there is a known issue where the onDeleted () method is not called during this call. To circumvent this problem, you can implement onReceive () to receive this onDeleted () callback as described in the Group post.

 

The most important AppWidgetProvider callback function is onUpdated (), because it is called when each App Widget is added to the host (unless you use a configuration activity). If your app
Widget to accept any user interaction events, then you need to register the event handler in this callback function. If your App Widget does not create temporary files or databases, or perform other work that requires cleaning, then onUpdated () may be the only callback function you need to define. For example, if you want an App with a button
Widget, when you click to start an activity, you can use the following AppWidgetProvider implementation:

public class ExampleAppWidgetProvider extends AppWidgetProvider {
 
    public void onUpdate (Context context, AppWidgetManager appWidgetManager, int [] appWidgetIds) {
        final int N = appWidgetIds.length;
 
        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i = 0; i <N; i ++) {
            int appWidgetId = appWidgetIds [i];
 
            // Create an Intent to launch ExampleActivity
            Intent intent = new Intent (context, ExampleActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity (context, 0, intent, 0);
 
            // Get the layout for the App Widget and attach an on-click listener to the button
            RemoteViews views = new RemoteViews (context.getPackageName (), R.layout.appwidget_provider_layout);
            views.setOnClickPendingIntent (R.id.button, pendingIntent);
 
            // Tell the AppWidgetManager to perform an update on the current App Widget
            appWidgetManager.updateAppWidget (appWidgetId, views);
        }
    }
}
This AppWidgetProvider only defines the onUpdated () method. To define a PendingIntent, start an activity and use setOnClickPendingIntent (int,
PendingIntent) method to attach it to the button of this App Widget. Note that it contains a loop that traverses all items in appWidgetIds. This is an IDs array. Each ID is used to identify an App Widget created by this provider. In this way, if the user creates more than one instance of this App Widget, they will be updated synchronously. However, for all App Widget instances, only one updatePeriodMillis schedule is managed. For example, if the update schedule is defined as every two hours, and the second instance of App Widget is added one hour after the first, then they will be updated according to the period defined by the first The two are ignored (they will be updated every 2 hours instead of every hour).

Note: Because this AppWidgetProvider is a broadcast receiver BroadcastReceiver, there is no guarantee that your process will continue to run after the callback function returns (see Application Fundamentals> Broadcast Receiver Lifecycle Application Fundamentals> Broadcast
Receiver Lifecycle for more information). If your App Widget setup process can last a few seconds (perhaps when performing a web request) and you ask your process to continue, consider starting a service in the onUpdated () method. From this service, you can execute your own app
Widget updates without worrying about AppWidgetProvider closing due to an Application Not Responding (ANR) error. See Wiktionary
sample's AppWidgetProvider, this is an example of App Widget running a Service.

See also the ExampleAppWidgetProvider.java example class.

Receive App Widget broadcast intent

 

AppWidgetProvider is just a convenience class. If you want to receive App Widget broadcast directly, you can implement your own BroadcastReceiver or rewrite onReceive (Context,
Intent) callback function. The four intentions you need to pay attention to are as follows:

· ACTION_APPWIDGET_UPDATE

· ACTION_APPWIDGET_DELETED

· ACTION_APPWIDGET_ENABLED

· ACTION_APPWIDGET_DISABLED

 

Create an App Widget configuration activity

If you want users to adjust the settings when adding a new App Widget, you can create an App Widget configuration activity. This activity will be automatically started by the App Widget host and allows the user to configure the available settings at creation time, such as App Widget color, size, update cycle, or other function settings.

This configuration activity should be declared as a generic activity in the Android manifest file. However, it will be started by the App Widget host through the ACTION_APPWIDGET_CONFIGURE activity, so this activity needs to accept this intent. such as:

<activity android: name = ". ExampleAppWidgetConfigure">
    <intent-filter>
        <action android: name = "android.appwidget.action.APPWIDGET_CONFIGURE" />
    </ intent-filter>
</ activity>
Similarly, the activity must be declared in the AppWidgetProviderInfo XML file, through the android: configure attribute (see Adding the AppWidgetProviderInfo Metadata above). For example, the configuration activity can be declared as follows:

<appwidget-provider xmlns: android = "http://schemas.android.com/apk/res/android"
    ...
    android: configure = "com.example.android.ExampleAppWidgetConfigure"
    ...>
</ appwidget-provider>
Note that this activity is declared with the full name, because it will be referenced from outside your package.

That's all you need to know about configuration activities at the beginning. Now you need a real activity. There are, but there are two important things to remember when you implement this activity:

• The App Widget host calls the configuration activity and the configuration activity should always return a result. This result should contain the App Widget ID that was passed through the intent to start the activity (extra_appwidget_id is saved in the intent additional section Intent
extras)

• The onUpdate () method will not be called when the App Widget is created (when a configuration activity starts, the system will not send ACTION_APPWIDGET_UPDATE broadcast). The configuration activity should be in the App
The widget is responsible for requesting an update from the AppWidgetManager when it is first created. However, onUpdate () will be called in subsequent updates-only the first time is ignored.

See the code snippet in the following section, this example shows how to return a result from the configuration and update the App Widget.

 

Update an App Widget from the configuration activity

 

When an App Widget uses a configuration activity, then when the configuration is completed, the App Widget should be updated by this activity. You can directly request an update in the AppWidgetManager to do so.

The following is a brief description of the process of properly updating the App Widget and closing the configuration activity:

First, get the App Widget ID from the intention to start this activity:
Intent intent = getIntent (); Bundle extras = intent.getExtras (); if (extras! = Null) {mAppWidgetId = extras.getInt (AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
2. Implement your App Widget configuration.

3. When the configuration is complete, obtain an AppWidgetManager instance by calling getInstance (Context):


AppWidgetManager appWidgetManager = AppWidgetManager.getInstance (context);
      4. Call updateAppWidget (int, with a RemoteViews layout
RemoteViews) Update App Widget:

RemoteViews views = new RemoteViews (context.getPackageName (), R.layout.example_appwidget); appWidgetManager.updateAppWidget (mAppWidgetId, views);
     5. Finally, create a return intent, set the result of the activity, and end the activity:


Intent resultValue = new Intent (); resultValue.putExtra (AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); setResult (RESULT_OK, resultValue); finish ();
Tip: When your configuration activity is first opened, set the activity result to RESULT_CANCELED. In this way, if the user returns from outside the activity before the end, the App Widget host will receive the configuration cancellation notification without adding the App Widget.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.