Android Study Notes: Home Screen Widgets (1): Widgets

Source: Internet
Author: User
Tags home screen

Android Study Notes: Home Screen Widgets (1): Widgets
What is Home Screen Widgets?

The Home screen Widget is called a Widget or a Chinese Widget. It is the views displayed on the Home page and the view data is updated through the background process.

In Android, AppWidgetManager manages the system's widgets. After the apk is installed, the widget name, icon, and occupied space are displayed in the widget list according to the Widget definition. In Android4.0, the widget is displayed in a grid, some OEM manufacturers will redesign the UI, and the display form of the widget list will be different.

We long press a widget in the widget list and drag it to the home page. In fact, AppWidgetManager creates an instance for this widget on the home page ). There can be multiple instances, and different instances are differentiated by widgetID.

Widgets define two important java classes. One is the widget aggregator activity. When a widget instance is generated, AppWidgetManager uses intent to initialize the configuration. The action is called android. appwidget. action. APPWIDGET_CONFIGURE: This java class is optional. Generally, configuration data is input and saved here. Because the amount of data is small, it can be easily stored in shared preference. If we create two widget instances, this configuration activity will be called twice.

A Java class is used to manage the lifecycle of widgets, including the processing of updating widgets when they are dragged to the home page and when they are dragged to the waste bin. It is an inheritance of AppWidgetProvider and essentially a broadcast receiver that triggers different callback functions based on the broadcast information sent by AppWidgetManager, such as the time interval for updating widget data (provided in the widget definition ), the generation and deletion of the widget instance, the generation of the first widget instance, and the deletion of the last widget instance.

The widget is generated on the page by AppWidgetManager according to the layout file provided in the widget definition, rather than directly generated by our code, therefore, we cannot directly operate on the view in the widget in the activity. We need to submit it to AppWidgetManager to process an instance through RemoteViews.

Small Example

We will use a small example to explain in detail how to create a widget. A small example is a birthday reminder.

When a widget instance is generated, the configuration activity is displayed. Enter the name and date of birth in the activity, press the "set" button to save the data in preference, and close the activity.

The top view of the widget displays widget_id: name. The left is the number of days from the next birthday. Click view on the right to open a webpage. The birth date is displayed below.


Define a broadcast Receiver

As mentioned above, Widgets have two important java classes. One is an optional activity for configuration, and the other is a broadcast receiver used to manage the wdiget lifecycle. The receiver receives broadcast messages from AppWidgetManager, to trigger various callback functions. We need to define these two java classes in AndroidManifest. xml. The class definition of the broadcast receiver is given below.



... ...
< CyclerAndroid: name = ". BirthDayWidgetProvider">

< Intent-filter>




This class inherits android. appwidget. AppWidgetProvider and sets related parameters through meta-data.

Here we will add some knowledge about meta-data. The most common method is to use key-value pairs, that is You can obtain this value in the component, for example, in activity:

ActivityInfo actInfo = mContext. getPackageManager (). getActivityInfo (getComponentName (), PackageManager. GET_META_DATA );
String msg = actInfo. metaData. getString ("activity_name ");

In service, ServiceInfo is used, ApplicationInfo is used in application, ActivityInfo is used in worker, but getReceiverInfo is used. If you need the ComponentName parameter, you can use new ComponentName (context, MyComponent. class.

Let's take a look at the Code related to android. appwidget. AppWidgetManager. java:

/**
* Sent when it is time to update your AppWidget.
*
*This may be sent in response to a new instance for this AppWidget provider having
* Been instantiated
, The requested {@ link AppWidgetProviderInfo # updatePeriodMillis update interval} having lapsed, or the system booting.
*......
*
* @ See AppWidgetProvider # onUpdate AppWidgetProvider. onUpdate (Context context, AppWidgetManager appWidgetManager, int [] appWidgetIds)
*/
Public static final String ACTION_APPWIDGET_UPDATE ="Android. appwidget. action. APPWIDGET_UPDATE";

/**
* Field for the manifest meta-data tag.
*
* @ See AppWidgetProviderInfo
*/
Public static final String META_DATA_APPWIDGET_PROVIDER ="Android. appwidget. provider";

In meta-data, android. appwidget. the provider is the keyword specified by Android. It is used to define the App Widget Provider information file in the corresponding resource. The file is located in xml/. In this example, It is res/xml/birthday_widget_provider.xml, define the widget parameters.

Android. appwdiget. action. APPWIDGET_UPDATE is one of the broadcast messages that the receiver listens to AppWidgetManger. Others also listen to ACTION_APPWIDGET_ENABLED and other messages. However, in the receiver, the system must specify ACTION_APPWIDGET_UPDATE to identify that the receiver is actually a widget, to add this widget to the widget list. Other messages to be listened to do not need to be listed here.

Definition of App widget provider

In manifest. xml, the file in which appwidget provider definition is defined is xml/birthday_width_provider.xml Based on meta-data. The content is as follows.


<Appwidget-providerXmlns: android = "http://schemas.android.com/apk/res/android"
Android: minWidth= "150dp"
Android: minHeight= "120dp"
Android: updatePeriodMillis= "43200000"
Android: initialLayout= "@ Layout/birday_widget"
Android: configure= "Cn. wei. flowingflying. testwidget. ConfigBirthDayWidgetActivity"
Android: previewImage= "@ Drawable/gift"
Android: resizeMode = "horizontal | vertical">

The widget size is 3 × 2 in the widget list. In xml, we define a length of DP and a width of DP. In fact, the space occupied by widgets in the Home Screen is calculated by grid, and each grid is 74dp × 74dp, the system allocates the desired grid. The average mobile phone network is 4x4, and the tablet is 8x7. In the book "Pro Android" gives advice for 74 N times minus 2dp (adapted border), while in Android developer website recommended definition of min length width is 70 * N-30, the following is an example:

In this example, the interval is 12 hours (43200000 ms ). Android strongly recommends a maximum of several times a day, not too many. Starting from Android2.0, the minimum value is 30 minutes.If it is set to 0, automatic update is not performed. We can use the AlarmManager class to control when to update the row. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Examples/dfTo6y/examples/B/JyezL9aOs16LS4qOsyOe5 + examples/examples + examples/ejrLKi1qez1s/examples/Co7o8L3A + examples = ". configBirthDayWidgetActivity "android: label =" Configure birthday gadgets ">




So far, we have completed the definition of the widget. Even if we have not specifically written any java class code, we can still package it and install it on the device. After installation, we can see our small example TestWidget In the widget list.

Widget appearance Definition

In appwidget-provider, android: initialLayout is used to define the widget's appearance. The corresponding layout/birday_widget.xml is as follows:


Android: layout_width = "150dp"
Android: layout_height = "120dp"
Android: orientation = "vertical"
Android: background = "@ drawable/box1">
Android: layout_width = "match_parent"
Android: layout_height = "30dp"
Android: text = "Anonymous"
Android: background = "@ drawable/box1"
Android: gravity = "center"/>
Android: layout_width = "match_parent"
Android: layout_height = "60dp">
Android: layout_width = "wrap_content"
Android: layout_height = "match_parent"
Android: text = "0"
Android: gravity = "center"
Android: textSize = "30sp"
Android: layout_weight = "50"/>
Android: layout_width = "wrap_content"
Android: layout_height = "match_parent"
Android: textSize = "20sp"
Android: text = "Buy"
Android: layout_weight = "50"
Android: background = "# FF6633"
Android: gravity = "center"/>

Android: layout_width = "match_parent"
Android: layout_height = "30dp"
Android: text = "2000/1/1"
Android: background = "@ drawable/box1"
Android: gravity = "center"/>"

Unlike the activity, you cannot directly obtain and control the view object in the code. You must use AppWidgetManager to indirectly control the view object using RemoteViews. Therefore, in the widget appearance definition, the view must support remote view, including FrameLayout, LinearLayout, RelativeLayout, AnalogClock, Button, Chronometer, ImageButton, ImageView, ProgressBar, TextView, ViewFlipper, ListView, GridView, StackView, and AdapterViewFlipper.

Android provides the guideline for widget design. For details, see http://developer.android.com/guide/practices/ui_guidelines/widget_design.html.

You can use android: background = "@ drawable/box1" to define the peripheral contour. Res/drawable/box1.xml contains the following content:



< StrokeAndroid: width = "4dp" android: color = "#888888"/>
< PaddingAndroid: left = "2dp" android: top = "2dp" android: right = "2dp" android: bottom = "2dp"/>
< CornersAndroid: radius = "4dp"/>


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.