A simple AppWidget

Source: Internet
Author: User

In fact, Appwidget is a small view that can be embedded into other applications and updated regularly. These views are called Widgets components. You can use AppwidgetProvider to publish Widgets, which can accommodate other appwidgets called Appwidget host.

 

1.1 register AppWidget in AndroidManifest. xml

[Html] view plaincopyprint?
<Cycler 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"/>
</Cycler>


<Cycler> android: name attribute is required, which specifies the AppwidgetProvider used by the Appwidget.

<Intent-filter> at least android: name = "android. appwidget. action. APPWIDGET_UPDATE" must be included. This attribute specifies that AppwidgetProvider receives the APPWIDGET_UPDATE broadcast, which is the only broadcast that needs to be explicitly stated. When necessary, AppWidgetManaget automatically broadcasts all appwidgets.

<Meta-data> the AppwidgetProviderInfo resource is specified. You need to set the attribute: android: name to specify the metadata name. Use android. appwidget. provider as descriptive data of AppwProviderInfo

Android: resource specifies the location of the AppwidgetProviderInfo resource

 

1.2 AppwidgetProviderInfo Metadata added
The basic attributes of an Appwidget are defined through AppwidgetproviderInfo, such as its minimal size layout, its initial layout, how long it will take to update the Appwidget, and (optional) configuring an Activity during creation. Defining an AppwidgetproviderInfo in an xml resource uses the <appwidget-provider> label and stores it in the res/xml/folder of the project. For example:

[Html] view plaincopyprint?
(Configuration file exclusive to AppWidget)
 
<? Xml version = "1.0" encoding = "UTF-8"?>
 
<Appwidget-provider
 
Xmlns: android = "http://schemas.android.com/apk/res/android"
 
Android: minWidth = "220dp"
 
Android: minHeight = "220dp"
 
Android: updatePeriodMillis = "86400000"
 
Android: initialLayout = "@ layout/firstappwidget"
 
Android: configure = "com. example. android. ExampleAppWidgetConfigure"/>

The updatePeriodMillis attribute defines how long the Appwidget should request an update from Appwidgetprovider. The actual Update time may not be guaranteed to be updated in a timely manner, and we recommend that you do not update it frequently as much as possible.
The Configure attribute is used to Configure the attributes of an AppWidget when you start an Activity before adding an Appwidget.

 

1.3 define layout for Appwidget
As long as you define layout using xml, it is very easy to define a layout for the appwidget. However, because the Appwidget layout is based on RemoteVIew, you can only use the layout (FrameLayout, LinearLayout, RelativeLayout) or view (AnalogClock, button, Chronometer, ImageButton, ImageView, ProgressBar, and TextView. Note: subclasses of these classes are also not supported ).

 

1.4 Use Appwidgetprovider
Appwidgetprovider is a subclass of BroadcastReceiver. This class processes the broadcast of Appwidget.

Appwidgetprovider only accepts broadcasts related to Appwidget, for example, Appwidget in update, deleted, enabled, and disable. When these broadcasts occur, AppWidgetProvider calls the callback method:

[Java] view plaincopyprint?
OnUpdate (Context, AppWidgetManager, int [])

You can call this method to update the Appwidget at intervals. The updatePeriodMillis attribute under AppwidgetproviderInfo is used to set the interval. The updatePeriodMillis attribute is also called when you add an Appwidget. If you have declared a configuration Activity, you will not call onUpdate when adding an Appwidget, but will still be called in subsequent updates.

OnDeleted (Context, int [])

When the Appwidget is deleted from the Appwidget host

OnEnabled (Context );

It is called when the Appwidget is created for the first time. For example, when a user adds two appwidgets, this method is called only for the first time. If you need to open a new database or other settings, and all the appwidgets only need to be set once, this is the last place to implement them.

OnDisabled (Context)

This API is called when the last Appwidget instance is deleted from the Appwidget host. Here, you can perform the opposite operations in onEnabled (Context), such as deleting a temporary database.

OnReceive (Context, Intent)

This method is called for each broadcast generation, and is called before the preceding method. This method is usually not required (this method will be analyzed in detail later ).

The most important callback in AppwidgetProvider is onUpdated (). If your Appwidget accepts user interaction events, it must be processed in this callback.

If you need an Appwidget with a Button, click the Button to start an Activity. The following describes how to implement AppwidgetProvider:

 

[Java]
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 tothe 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
WidgetappWidgetManager. updateAppWidget (appWidgetId, views );
}
}
}

1.5 create an Appwidget Configuration Activity

This Activity will be automatically started through Appwidget. You can set useful parameters for Appwidget, such as the color, size, Update Time, and other attributes of Appwidget.

Defining this Activity in AndroidManifes. xml is basically the same as defining the Activity in general. The Appwidget host needs an Action to start this Activity, so:

 

[Java]
<Activity android: name = ". ExampleAppWidgetConfigure">
<Intent-filter>
<Action android: name = "android. appwidget. action. APPWIDGET_CONFIGURE"/>
</Intent-filter>
</Activity>

Similarly, this Activity must define android: configure in the AppwidgetProviderInfo XML file.

It is worth noting that the Appwidget host calls the configuration Activity, and the configuration Activity must return a result (which must contain the Appwidget ID) saved in the Intent extras as EXTRA_APPWIDGET_ID

 

1.6 Update the Appwidget through configuration Activity
Get Appwidget ID

[Java] www.2cto.com
Intent intent = getIntent ();
Bundle extras = intent. getExtras ();
If (extras! = Null ){
MAppWidgetId = extras. getInt (
AppWidgetManager. EXTRA_APPWIDGET_ID, AppwidgetManaget. INVALID_APPWIDGET_ID );
}

Set Appwidget Parameters

The setting is complete. Get the AppwidgetManager instance through getInstance (Context ).


[Java]
AppWidgetManager appWidgetManager = AppWidgetManager. getInstance (context );
Update the Appwidget by calling updateAppWidget (int, RemotrViews ).


[Java]
RemoteViews views = new RemoteViews (context. getPackageName (),
R. layout. example_appwidget );
AppWidgetManager. updateAppWidget (mAppWidgetId, views );

Create a returned Intent and end the Activity

[Java]
Intent resultValue = new Intent ();
ResultValue. putExtra (AppWidgetManager. EXTRA_APPWIDGET_ID, mAppWidgetId );
SetResult (RESULT_ OK, resultValue );

Android: initialLayout = "@ layout/firstappwidget" specifies the layout file firstappwidget. xml below.
[Java]
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">
<TextView android: id = "@ + id/tvMsg" android: layout_width = "fill_parent"
Android: layout_height = "wrap_content" android: textSize = "20dp"
Android: textColor = "# F00"/>
</LinearLayout>
Author: fangchongbory

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.