Android Desktop Plugin App widget usage analysis _android

Source: Internet
Author: User
Tags sqlite database

This example describes the Android Desktop plugin app widget usage. Share to everyone for your reference, specific as follows:

application window Widget App Widgets

The application window widget (widget) is a tiny application view that can be embedded in other applications (such as the desktop) and receive periodic updates. You can use an app widget provider to publish a widget. Application components that can accommodate other app widgets are called App widget hosts. The screenshot below shows a music app Widget.

Appwidget

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 objects

Describes an app widget metadata, such as the layout of the app widget, the frequency of updates, and the Appwidgetprovider class. This should be defined in XML.

Implementation of Appwidgetprovider Class

Define basic methods to allow you to programmatically connect to the app widget, which is based on broadcast events. Through it, you will receive a broadcast notification when the app widget is updated, enabled, disabled, and deleted.

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 active activity that loads when the user adds the app widget and allows him to modify the settings of the app widget when it is created.

The following sections describe how to build these components:

Declare an application widget in the manifest

First, declare the Appwidgetprovider class in the application Androidmanifest.xml file, 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 < src= "http:// Hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js "type=" Text/javascript "> < srcsrc=" http:// Hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/langs/zh.js "type=" Text/javascript ">"/>
</ Receiver>

The <receiver> element requires the Android:name attribute, which specifies the Appwidgetprovider used by the app widget.

The <intent-filter> element must include a <action> element that contains the Android:name attribute. This element specifies that Appwidgetprovider accepts action_appwidget_update broadcasts. This is the only broadcast you must explicitly declare. When needed, Appwidgetmanager automatically sends all other app widgets to Appwidgetprovider.

The <meta-data> element specifies the Appwidgetproviderinfo resource and requires the following properties:

· android:name– Specifies the metadata name.
· android:resource– Specifies the Appwidgetproviderinfo resource path.

Increase the Appwidgetproviderinfo meta data

Appwidgetproviderinfo defines the basic features of an app widget, such as minimum layout size, initial layout resources, refresh frequency, and (optionally) a configuration activity that is loaded when it is created. Define the Appwidgetproviderinfo object in the XML resource using a separate <appwidget-provider> element and save it to the project's res/xml/directory.

Like what:

<appwidget-provider xmlns:android= "http://schemas.android.com/apk/res/android"
  android:minwidth= "294DP" <!--density-independent pixels-->
  android:minheight= "72DP"
  android:updateperiodmillis= "86400000" <!--once per day-->
  android:initiallayout= "@layout/example_appwidget"
  android:configure= " Com.example.android.ExampleAppWidgetConfigure ">
</appwidget-provider>

The following is a summary of the <appwidget-provider> properties:

· The values of the MinWidth and MinHeight properties specify the minimum area required for this app widget layout.

The default app widgets's desktop location is based on the exact height and width of the cell grid. If the minimum length of the app widget and the size of these mesh cells do not match, the app widget will shrink to the nearest cell size. (See app Widget Design guidelines for more information on desktop unit sizes)

Because the desktop layout direction (and thus the size of the unit) can vary, according to the thumb rule, you should assume that the worst-case unit size is 74 pixels high and wide. However, you must subtract 2 from the final dimension to take into account any rounding errors that occur during the pixel calculation. To find the minimum width and height regardless of pixel density, use this formula:

(Number of cells * 74)-2

Following this formula, you should use 72DP for each unit height, 294DP for four cell widths.

· The Updateperdiodmillis property defines the frequency with which the app widget framework calls the OnUpdate () method to request an update from the Appwidgetprovider. The actual update time is not as accurate, and we recommend that the update frequency be as low as possible-perhaps not more than once per hour to conserve power. You may also allow users to adjust this frequency in their configuration-some may want to quote a stock every 15 minutes or four times a day.
· The Initiallayout attribute points to resources that define the layout of the app widget.
· The Configure property defines an activity that starts when the user adds the app widget and thinks he or she configures the app widget feature. This is optional (read the following creating an App Widget Configuration activity).

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

Create the App widget layout

You must define an initial layout for your app widget in XML and save it to the res/layout/directory of your project. You can use the view objects listed below to design your app widget, but before you do, read and understand the app widget designs guidelines.

If you are familiar with declaring layouts in XML, it is easy to create this app widget layout. 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 the following layout class:

· Framelayout
· LinearLayout
· Relativelayout

And the following widget classes:

· AnalogClock
· Button
· Chronometer
· ImageButton
· ImageView
· ProgressBar
· TextView

Derivation of these classes is not supported.

Using the Appwidgetprovider class

You must declare your Appwidgetprovider class to be a broadcast receiver by using the <receiver> element in the manifest file (see the declaring an App Widget in the Manifest above).

The Appwidgetprovider class extension Broadcastreceiver is a simple class to handle app widget broadcasts. Appwidgetprovider only receives event broadcasts related to this app widget, such as the app widget being updated, deleted, enabled, and disabled. When these broadcast events occur, Appwidgetprovider receives the following method call:

OnUpdate (context, Appwidgetmanager, int[])

This method is used to update the app Widget on an interval-time interval with the Updateperiodmillis attribute defined in Appwidgetproviderinfo (see Adding Appwidgetproviderinfo meta data). This method will also be invoked when the user adds the app widget, so it should perform the underlying settings, such as defining an event handler for the view and starting a temporary services service, if needed. However, if you have declared a configuration activity, this method will not be invoked when the user adds the app widget, but only on subsequent updates. The configuration activity should be responsible for performing the first update when the configuration is complete. (see the following to create an app widget configuration event creating an app widget Configuration activities.) )

Ondeleted (context, int[])

Called when the app widget is removed from the host.

Onenabled (context)

Invoked when an app widget instance is created for the first time. For example, if a user adds two instances of your app widget, it is invoked only the first time. If you need to open a new database or perform other settings that only need to happen once for all of the app widget instances, this is a good place to do the job.

Ondisabled (context)

Called when the last instance of your app widget is removed from the host. You should do some cleanup work in the onenabled (context), such as deleting a temporary database.

OnReceive (context, Intent)

This is invoked when each broadcast is received, and before the callback function above. You don't usually need to implement this method, because the default Appwidgetprovider implementation filters all app Widget broadcasts and invokes the above method appropriately.

Note: In Android 1.5, there is a known problem that the ondeleted () method is not invoked at the time of the call. To circumvent this problem, you can implement OnReceive () to receive this ondeleted () callback as described in group post.

The most important Appwidgetprovider callback function is onupdated () because it is invoked when each app widget is added to the host (unless you use a configuration activity). If your app Widget accepts any user interaction events, then you need to register the event handler in this callback function. If your app widget doesn't create temporary files or databases, or performs other work that needs to be cleaned up, then onupdated () may be the only callback function you need to define. For example, if you want an app Widget with a button that starts an activity when clicked, you can use the following appwidgetprovider to implement:

public class Exampleappwidgetprovider extends Appwidgetprovider {public void OnUpdate (context context, appwidgetmanage
    R 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++) {in
      T appwidgetid = appwidgetids[i];
      Create a 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 a On-click listener to the button remoteviews views = new Remotevie
      WS (Context.getpackagename (), r.layout.appwidget_provider_layout);
      Views.setonclickpendingintent (R.id.button, pendingintent); Tell the Appwidgetmanager to perform a update on the current App Widget Appwidgetmanager.updateappwidget (APPWIDG
    Etid, views);

 }
  }
}

This appwidgetprovider only defines the onupdated () method, in order to define a pendingintent, to start an activity and use setonclickpendingintent (int, pendingintent) method to attach it to the button on the app widget. Note that it contains a loop that iterates through all the items in the Appwidgetids, an array of IDs, each identifying an app Widget created by this provider. This way, if the user creates more than one instance of the app widget, they will be updated synchronously. However, for all instances of the app widget, only one updateperiodmillis schedule is managed. For example, if this update schedule is defined as every two hours, and the second instance of the app widget is added after the first one hour, and they are updated with the first defined cycle and the second is ignored (they will all be updated every 2 hours, not hourly).

Note: Because this appwidgetprovider is a broadcast receiver broadcastreceiver, it is not guaranteed that your process will continue to run after the callback function returns (see Application Basics > Broadcast Receiver Lifecycle Application Fundamentals > Broadcast Receiver lifecycle to get more information). If your app widget setup lasts for a few seconds (perhaps when you execute a Web request) and you ask your process to continue, consider starting a service in the OnUpdated () method. From this service, you can perform your own app widget update without having to worry about the Appwidgetprovider shutdown due to an application that has no response error application not responding (ANR). See Wiktionary sample ' s Appwidgetprovider, an example of an app widget running a service.

See likewise the Exampleappwidgetprovider.java example class.

Receive App Widget broadcast intent

Appwidgetprovider is just a simple class. If you want to receive the app Widget broadcast directly, you can implement your own broadcastreceiver or rewrite the onreceive (context, Intent) callback function. The 4 intentions you need to be aware of 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 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 users to configure settings that are available when they are created, such as app widget color, size, update cycle, or other feature settings.

This configuration activity should be declared as a generic activity in the Android manifest file. However, it will be initiated by the app widget host through the action_appwidget_configure activity, so this activity needs to be accepted. Like what:

<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 Add appwidgetproviderinfo metadata above adding the Appwidgetproviderinfo Metadata). For example, a 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, as it will be referenced from outside your package.
That's all you need to know about the configuration activity at first. Now you need a real activity. There are, however, two important things to remember when you implement this activity:

The App widget host uses configuration activity and the configuration activity should always return a result. This result should contain the APP Widget ID (with extra_appwidget_id saved in the intent) by the intention to launch the activity intent In extras)

• The OnUpdate () method will not be invoked when the App widget is created (the system will not send action_appwidget_update broadcasts when a configuration activity is started). Configuration activity should be in App widget The first time you are created, you are responsible for requesting an update from the Appwidgetmanager. However, OnUpdate () will be invoked in subsequent updates-only the first time.

See the code snippet in the following section, which 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, it should be updated by this activity at the end of the configuration. You can request an update directly from the Appwidgetmanager to do so.

The following is an overview of the process of updating the app Widget appropriately and shutting down the configuration activity:

1. First, get the app Widget ID from the intent to launch 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 a Appwidgetmanager instance by calling getinstance (context):

Copy Code code as follows:
Appwidgetmanager Appwidgetmanager = appwidgetmanager.getinstance (context);

4. Call Updateappwidget (int, remoteviews) to update the app Widget with a remoteviews layout:

Remoteviews views = new Remoteviews (Context.getpackagename (), r.layout.example_appwidget);
Appwidgetmanager.updateappwidget (Mappwidgetid, views);

5. Finally, create the return intent, set the results of the activity, and end this activity:

Intent resultvalue = new Intent ();
Resultvalue.putextra (appwidgetmanager.extra_appwidget_id, mappwidgetid);
Setresult (RESULT_OK, resultvalue);
Finish ();

tip: When your configuration activity is opened for the first time, set the activity result to result_canceled. Thus, if the user returns from outside the activity before the end, the app widget host receives a configuration cancellation without adding the app widget.

For more information on Android-related content readers can view the site: "Android View tips Summary", "Android Programming activity Operating Skills Summary", "Android operation SQLite Database Skills Summary", " Android operation JSON format data tips summary, "Android Database Operation skills Summary", "Android File Operation skills Summary", "Android programming development of SD card Operation Summary", "Android Development introduction and Advanced Course", " Android Resource Operation tips Summary and the "Android Controls usage Summary"

I hope this article will help you with the Android program.

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.