Start from scratch-go deep into Android (practice-let's start coding-android framework learning-7.app widgets)

Source: Internet
Author: User
Tags home screen
Chapter 2 App Widgets

APP widgets is a micro view of an application. It can be embedded into other applications (such as the home screen) and can be updated regularly. You can publish an app widget, which is called the window user interface. An application component that supports other applications called app widgets as the host of the app widget ). The following is the app widget that displays music.

This document describes how to publish and use app widgets in an application.

7.1 basic knowledge

To create an app widget, you need to know the following:

◆ Appwidgetproviderinfo object:
Describes the metadata of an app widget, such
Widget layout, update frequency, and appwidgetprovider class. All should be defined in XML.
◆ Implementation of the appwidgetprovider class:
Defines an Interface Method Based on broadcast events and app widgets. You will receive a broadcast to update, enable, disable, and delete the app widget.
◆ View layout:
Define the app widget layout in XML.
In addition, you can also implement activities that can be configured by APP widgets. When a user adds your app widget and allows him or her to modify the settings during creation, the configurable activity is started.
This document describes how to publish and use app widgets in an application.

7.2 declare app widgets in manifest. xml

First, the appwidgetprovider class should be declared in the androidmanifest. xml file of your application. For example, the code list is 7-1:

<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>

 

Code List 7-1

<Cycler> the Android: Name attribute required by the node. appwidgetprovider is specified in the app widget. The <intent-filter> node must contain the name attribute of the <action> node. This attribute specifies that appwidgetprovider accepts action_appwidget_update broadcast. This is the only broadcast, and you must make it clear. It is necessary to automatically send other app widgets to appwidgetprovider in appwidgetmanager. <Meta-data> the following attributes are required for the appwidgetproviderinfo resource specified by the node:

Android: name-the name of the specified metadata. Use Android. appwidget. provider to identify

◆ Appwidgetproviderinfo descriptor data.

◆ Android: resource-the resource location of the specified appwidgetproviderinfo.

7.3 add appwidgetproviderinfo metadata

Appwidgetproviderinfo is the essence of defining app widgets, such as its minimum layout size, initial layout resources, how to update app widgets, and (optional) Configure activity at creation. Define the appwidgetproviderinfo object in the XML resource file, and use the <appwidget-provider> node and save it in the Res/XML/folder of the project. As shown in code list 7-2:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"    android:minWidth="294dp"    android:minHeight="72dp"    android:updatePeriodMillis="86400000"    android:previewImage="@drawable/preview"    android:initialLayout="@layout/example_appwidget"    android:configure="com.example.android.ExampleAppWidgetConfigure"     android:resizeMode="horizontal|vertical"></appwidget-provider>

 

Code List 7-2

The following is a summary of the <appwidget-provider> attribute. Before that, you 'd better read the first part of the widget Design chapter:

◆ By default, the minwidth and minheight values of APP widgets specify the minimum occupied space. appwidgets is at the home screen position by default, and a grid with a clear height and width is displayed in the cell based on the window. If the minimum width or height of an app widget does not match the cell size, the app widget size is rounded up to the nearest cell size.

Note: To make app widgets easier to be transplanted to different devices, the minimum size of APP widgets should not be greater than 4x4 cells.

◆ The minresizewidth and minresizeheight attributes specify the absolute minimum size of the app widget. These values should be within the specified size, otherwise the application component will be unrecognizable or used in other ways. In android3.1, you can use these attributes to adjust the widget size, which may be smaller than the minwidth and minheight attributes defined by default.

◆ Updateperiodmillis attribute definition, often in the app widget framework, should be updated from the appwidgetprovider request by calling the onupdate () callback method. In fact, the update accuracy cannot be guaranteed. We recommend that you do not update the updates as much as possible or not more than once every hour to save the battery. You can also allow the user to adjust the frequency in configuration-some, such as the quote machine of the certificate holder. Some users may want to update the frequency once every 15 minutes, while others may want to update only four times a day.

Note: If the device is asleep and it is an update time (defined as updateperiodmillis), the device will be awakened for update. If you do not update the battery every hour, this may not cause major problems to the battery life. However, if you need to update the device frequently or you do not need to update the device, but the device is asleep, you can execute the update based on the alarm instead. To do this, set an intent to use alarmmanager when your appwidgetprovider receives an alarm. Set the alarm type to elapsed_realtime or RTC. When an alarm is received, the device is woken up. Set updateperiodmillis to zero ("0 ").

◆ The attributes of initiallayout point to the layout resource, which defines the layout of the app widget.

◆ Define attributes when the activity is started. You can add app widgets to configure app widget attributes. This is optional.

◆ After configuring the previewimage attribute, you can specify what the app widget icon looks like. When this app widget is selected, You can preview it. If no icon is provided, the user thinks that laucher is your application icon. This field corresponds to Android: previewimage in the androidmanifest. xml file of the <javaser> element. Introduced in android3.0.

◆ Introduced in Android 3.0, the view ID of the app widget subview specified by the autoadvanceviewid attribute.

◆ Introduced in Android 3.1, this resizemode attribute specifies a widget that can adjust rules. You can use this property to adjust widgets on the home screen, such as horizontal, vertical, or two axes. You can press a widget to display its adjusted interface, and then drag the horizontal and/or vertical control keys to change the size of the layout grid. The resizemode attribute values include "horizontal", "vertical", and "NONE ". Both are like "Horizontal | vertical ".

7.4 create an app widget Layout

You must define the initial layout for your app Widgets. You can define the layout in XML and save it in the Res/layout/directory of the project. You can use the following view objects to design your app Widgets. Before you design your app widgets, read and understand the design principles of APP widgets. If you are familiar with the XML layout, it is easy to create an app widget layout. However, you must know that the layout of the app widget is based on the remoteviews class. It does not support various la s or view widgets.
A remoteviews object supports the following layout classes:

Framelayout

Linearlayout

Relativelayout

The following view supports widgets:

Analogclock

Button

Chronometer

Imagebutton

Imageview

Progressbar

Textview

Viewflipper

Listview

Gridview

Stackview

Adapterviewflipper

However, none of these classes are supported.

1.Add margins to app Widgets

Widgets should not be scaled to the edge of the screen and should not be refreshed together with other widget views, so you should add margins in your widget box. Since Android 4.0, app widgets provide an automatic filling frame between widgets and an app widget's surrounding box, so that you can better adjust other widgets and icons on the home screen. To obtain this function, you need to set the targetsdkversion of the application to 14 or higher.
In earlier versions, it is easy to write a layout and customize the margins. There is no additional margin in android4.0 or later versions. The steps are as follows:
◆ Set the targetsdkversion value of the application to 14 or higher.
◆ Create a layout to reference dimension resources, as shown in code listing 7-3:

<FrameLayout  android:layout_width="match_parent"  android:layout_height="match_parent"  android:padding="@dimen/widget_margin">   <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal"    android:background="@drawable/my_widget_background">    …  </LinearLayout> </FrameLayout>

 

Code List 7-3

◆ Create two dimensions resources, one in RES/values/provides custom margins before Android 4.0, one in RES/values-v14/does not provide additional padding for android4.0widgets:
Res/values/dimens. xml:

<dimen name="widget_margin">8dp</dimen>

Res/values-v14/dimens. xml:

<dimen name="widget_margin">0dp</dimen>

 

7.5 use the appwidgetprovider class

First, you must implement the appwidgetprovider class declared in the androidmanifest <er ER> node (see "7.2 declare app widgets in manifest. xml" in this chapter ").

Appwidgetprovider inherits broadcastreceiver, which is very convenient for processing app widget broadcasts. Appwidgetprovider only receives event broadcasts related to app widgets. For example, when app widgets are updated, the related app widgets are deleted, enabled, and disabled. When these broadcast events occur, appwidgetprovider will call the following methods:
◆ Onupdate ()

In this way, appwidgetproviderinfo is updated by the interval defined by the updateperiodmillis attribute. When a user adds an app widget, this method is also called. Therefore, basic settings should be performed, such as defining view event processing. If necessary, a temporary service should also be started. However, if you have declared the configured activity, this method will not be called when you add app widge, but will be updated later. After the activity is configured, it performs the first update.

◆ Onappwidgetoptionschanged ()

It is called when wodget is adjusted for the first time. You can use this callback to display or hide the content. You can use getappwidgetoptions () to obtain the size range. It returns a bundle. You can use the following string key to obtain the value:

Appwidgetmanager. option_appwidget_min_width-minimum value of the current width, in the unit of DP

Appwidgetmanager. option_appwidget_min_height-minimum value of the current height, in the unit of DP

Appwidgetmanager. option_appwidget_max_width-maximum value of the current width, in the unit of DP

Appwidgetmanager. option_appwidget_max_height-maximum value of the current height, in the unit of DP

Android4.1 introduces this method. Note:

◆ Ondeleted (context, int [])

It is called every time an app widget is deleted from the app widget host.

◆ Onenabled (context)

Called when an app widget instance is created for the first time. For example, if you add two instances for the same app widget, this is also called once. If you need to open a new database or perform other settings, the instance is very good in this place.

◆ Ondisabled (context)

When the last app widget instance is
Called when the widget is deleted on the host. The ondisabled (context) method is used to clean up, for example, deleting a temporary database.

◆ Onreceive (context, intent)

It can be understood as a universal broadcast receiving interface, the callback of each method above. You usually do not need to implement this method, because the default appwidgetprovider implements the filter to broadcast all app widgets and calls the above method as appropriate.

 

When each app
When a widget is added to a host, the most important thing is the appwidgetprovider onupdate () method callback (unless you use a configured activity ). If your app widget accepts any user interaction event, you need to register the event processor during callback. If your app
Widgets cannot create temporary files or databases, or execute other work. You need to be clear that the onupdate () method may be the only callback method you need to define. For example, if you want a button on an app widget to start an activity when you click it, You can implement appwidgetprovider in this way, as shown in code listing 7-4:

public class ExampleAppWidgetProvider extends AppWidgetProvider {     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];                 Intent intent = new Intent(context, ExampleActivity.class);            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);            views.setOnClickPendingIntent(R.id.button, pendingIntent);            appWidgetManager.updateAppWidget(appWidgetId, views);        }    }}

 

Code List 7-4

In the above Code List 7-4, appwidgetprovider only defines the onupdate () method. Its purpose is to define a pendingintent to start an activity and use setonclickpendingintent (INT, pendingintent) to append it to the app widget button. Note: In appwidgetids, it contains a loop to traverse each entry. This is the ID of an array and determines each app widget. In this way, if you create instances of multiple app widgets, they are updated at the same time. However, only one updateperiodmillis schedule will manage all app widgets. For example, if an update plan is defined as every two hours, wait for one hour after the first instance to add the second instance, both of them will use the first cycle, while the second update cycle will be ignored. For more information, see the example of apidemos \ SRC \ com \ example \ Android \ APIs \ appwidget.

Appwidgetprovider is a convenient class. If you want to directly receive app widget broadcasts, You can implement your own broadcastreceiver or overwrite onreceive (context, intent) method. Note the following intent:

Action_appwidget_update

Action_appwidget_deleted

Action_appwidget_enabled

Action_appwidget_disabled

Action_appwidget_options_changed

7.6 create an activity for app widget Configuration

If you want to configure a user when a new app widget is added, you can create an app widget to configure the activity. The current acitivity will automatically start the app widget host, and allow users to configure the color, size, update cycle, or other function settings of the app widget during creation. This configuration activity should be declared as a standard activity in the android manifest file. However, it will be started through the app widget host using action_appwidget_configure action, so this activity needs to receive such intent. As shown in code list 7-5:

<activity android:name=".ExampleAppWidgetConfigure">    <intent-filter>        <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>    </intent-filter></activity>

 

Code List 7-5

In addition, the activity must declare the Android: Configure attribute in the appwidgetproviderinfo XML file (see "add appwidgetproviderinfo metadata" in the previous section "). For example, the activity declaration to be configured is shown in the code list 7-6:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"    ...    android:configure="com.example.android.ExampleAppWidgetConfigure"     ... ></appwidget-provider>

 

Code List 7-6

Note that this activity declares a fully qualified namespace because it is referenced from an external package.
You need to start a configuration activity. What you need now is the actual activity. However, there are two important things to remember when you implement an activity:

◆ This app widget host calls the configuration activity, and the configuration activity should always return a result code. The result code should include the app widget ID.

◆ When an app widget is created, the onupdate () method will not be called (when the activity is started, the system will not send the action_appwidget_update broadcast ).

This is the role of activity configuration. It requests updates when appwidgetmanager is created for the first time from the app widget. However, the onupdate () method will call subsequent updates, which will only be skipped for the first time.

See the following code snippet to see how it returns the results of the configured and updated app widgets.

When an app widget configures an activity, it updates the app widget after the activity is configured. You can directly update from appwidgetmanager through requests.
1. Get the app widget ID from the activity started with intent:

Intent intent = getIntent();Bundle extras = intent.getExtras();if (extras != null) {    mAppWidgetId = extras.getInt(            AppWidgetManager.EXTRA_APPWIDGET_ID,             AppWidgetManager.INVALID_APPWIDGET_ID);}

 

2. Execute your app widget configuration.
3. After the configuration is complete, call getinstance (context) to obtain an appwidgetmanager instance:

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

4. Update the app widget using the remoteviews layout by calling updateappwidget (INT, remoteviews:

RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.example_appwidget);appWidgetManager.updateAppWidget(mAppWidgetId, views);

5. Finally, create the returned intent, set the result of the activity, and terminate the activity:

Intent resultValue = new Intent();resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);setResult(RESULT_OK, resultValue);finish();

 

7.7 set a preview Image

The previewimage attribute is introduced after android3.0, which specifies an appwidget thumbnail. Next let's take a look at the code list 7-7 to see how it is set.

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"  ...  android:previewImage="@drawable/preview"></appwidget-provider>

Code List 7-7

To help your appwidget (specified in the previewimage field) create a preview image, the android simulator contains an application called "widget preview ". To create a preview image, start the application, select the appwidget of your application, set the desired preview image, and save it, and place it under the drawable resource of your application.

 

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.