Android Development 5: Application window Widget app widgets implementation (with demo) _android

Source: Internet
Author: User
Tags time interval

Objective

This is the main implementation of an Android application, static broadcast, dynamic broadcast two ways to change the content of the widget, that is, in the blog on the basis of the experiment to modify, so the focus of this experiment is the realization of appwidget small parts ~

First, let's simply say what the widget is.

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.

A widget is something that displays information on the desktop, and it jumps into a program by clicking the widget. And the system's own program, the typical widget is music, the android built in the video playback applet. This is a typical Widget+app application. Is that a program can be started either through the widget or through the app. Widget is a appwidgetprovider+ UI display (a lot of intent in advance), the information on the interface can be changed by program control, click the widget, the controls on the can only fire send a intent, Or issue a service launch notification. and Appwidgetprovider can intercept the intent and do the appropriate processing (such as displaying new information).

Basic knowledge

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.

Widget add: Long Press Menu key, click Widgets option. Find the corresponding widget and drag it into the desktop. A slightly different version of the API is displayed for different versions.

The typical Android Widget has three main components, a border, a frame and graphics controls, and other elements. When you create the Widget class in Android Studio, the related files are generated directly.

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 "/>
</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.

1. Widget layout file Widget_demo.xml, there is a imageview in the layout, a TextView. Requirements: The text color is red, the size is 20DP, the whole background is transparent. The final effect is as follows:

2. Add 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.

Widget content Provider File Widget_demo_info.xml, edit the file, set its size properties and layout, as shown in the following figure:

Wherein, the minwidth is the minimum width, the minheight is the minimum height, and the initiallayout is the initial layout.

3. Modify the Widgetdemo.java code, rewrite the OnUpdate method, add events for the Widget so that you can return to the main page.

Here is a way to use a user program to access the main screen and modify the content of specific areas: RemoteView architecture. The RemoteView architecture allows users to update the main screen View, click the Widget to activate the Click event, and Android forwards it to the user program, which is handled by the Appwidgetproviders class, allowing the user program to update the main screen Widget.

Pendingintent is a special kind of Intent. The main difference is that Intent's execution is immediate, and Pendingintent's execution is not immediate. The static method of using the method class is getactivity (context, int, Intent, int), corresponding to the operation of the Intent jump to an activity component.

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.

4. Rewrite the OnReceive method

Rewrite the OnReceive method in the Widget class, where you need to use the RemoteView and Bundle. Data processing when a corresponding broadcast is received.

The main functions used in the IF condition statement are: Settextviewtext, Setimageviewresource. The Widget is then updated with the Appwidgetmanager class.

Experimental content

Implementation of an Android application, static broadcast, dynamic broadcast two ways to change the content of the widget. In the last experiment based on the modification, so some of the static dynamic broadcast content will be abbreviated.

Specific requirements:

(1) The interface to be seen when the application is started.

Widget initial conditions are as follows

(2) Click the static registration button to jump to the following interface.

Click on the form item. such as banana. The widget will change accordingly. Click on the Widget picture to jump back to the main page

(3) Click the Dynamic Registration button to jump to the following interface. The following features are implemented:

A) You can edit the broadcast information and click the Send button to send the broadcast.

B Set a button to register and unregister the broadcast receiver.

c If the broadcast receiver has been registered, the broadcast information sent out can update the text content on the Widget on the desktop and update it as the default dynamic picture in time.

D Click on the Widget image to jump back to the main page.

Experiment steps

First, create widget classes in Android Studio and directly generate related files, including interface layout XML files, The widget's provider file information (XML) and a receiver tag in the project's Androidmenifest.xml file require us to add a filter update event and point to the widget class we created earlier.

In the Androidmenifest.xml file, Intent-filter filters the Appwidget_update event, which is an update event triggered by the system, and each widget must contain this event The meta-data tag describes the widget's configuration file, which describes some basic information about the widget (which is also filtered staticreceiver in Intent-filter because of the need to be implemented in static registration):

<receiver
   android:name= ". Myappwidget "
   android:enabled=" true "
   android:exported=" true ">
   <intent-filter>
    < Action android:name= "Android.appwidget.action.APPWIDGET_UPDATE"/>
    <action android:name= " Com.example.yanglh6.myapplication4.staticreceiver "/>
   </intent-filter>
   <meta-data
    Android:name= "Android.appwidget.provider"
    android:resource= "@xml/my_app_widget_info"/>
</ Receiver>

Next, write the widget's provider file information (XML) as required, MinWidth and minheight are the minimum width and height of the widget, the value is a reference value, the system will change according to the actual situation, The Initiallayout property indicates the Widge view layout file, and the Updateperiodmillis property is the time, in milliseconds, that the widget updates every how often:

<?xml version= "1.0" encoding= "Utf-8"?> <appwidget-provider xmlns:android=
"http://schemas.android.com" /apk/res/android "
 android:initialkeyguardlayout=" @layout/my_app_widget "
 android:initiallayout=" @layout /my_app_widget "
 android:minheight=" 55DP "
 android:minwidth=" 200DP "
 android:previewimage=" @drawable Example_appwidget_preview "
 android:resizemode=" horizontal|vertical "
 android:updateperiodmillis=" 86400000 "
 android:widgetcategory=" Home_screen "></appwidget-provider>

The next step is the layout of the interface, which requires a ImageView control and a TextView control in this example:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
 android:layout_width= "Match_ Parent "
 android:layout_height=" match_parent "
 android:gravity=" center ">

 <imageview
  Android:id= "@+id/widgetimage"
  android:layout_width= "60DP"
  android:layout_height= "60DP"
  android: gravity= "center"
  android:src= "@mipmap/apple"/>

 <textview android:id= "
  @+id/widgetname"
  android:layout_width= "wrap_content"
  android:layout_height= "60DP"
  android:textcolor= "@color/red "
  android:textsize=" 20DP "
  android:layout_torightof=" @+id/widgetimage "
  android:text=" Apple "
  android:gravity= "center"/>

</RelativeLayout>

The layout file implements a layout of the following diagram:

Then, in the widget, rewrite the OnUpdate method to add events to the widget so that you can return to the main page. Here you need to use a method to access the main screen and modify the content of a particular area RemoteView the schema. The RemoteView architecture allows users to update the main screen view, click the widget to activate the Click event, and Android forwards it to the user program, which is handled by the Appwidgetproviders class, allowing the user program to update the main screen widget.

@Override public
 void OnUpdate (context context, Appwidgetmanager Appwidgetmanager, int[] appwidgetids) {
  Super.onupdate (context, Appwidgetmanager, appwidgetids);
  Intent clickint = new Intent (context, mainactivity.class);
  Pendingintent pendingintent = pendingintent.getactivity (context, 0, clickint, 0);
  Remoteviews view = new Remoteviews (Context.getpackagename (), r.layout.my_app_widget);
  View.setonclickpendingintent (R.id.widgetimage, pendingintent);
  Appwidgetmanager.updateappwidget (appwidgetids, view);
 

Next, rewrite the OnReceive method in the Widge class, where you need to use RemoteView and bundle. Data processing when a corresponding broadcast is received (because we point the Appwidget_updat event and Staticreceiver to the Widge class as we register in the Androidmenifest.xml file), So here we delete the Staticreceiver class and add the part of the OnReceive function rewrite inside the widget class:

@Override public void OnReceive (context context, Intent Intent) {log.i ("Debug", Intent.tostring ());
  Super.onreceive (context, intent);
  Remoteviews view = new Remoteviews (Context.getpackagename (), r.layout.my_app_widget);
  Bundle Bundle = Intent.getextras ();
  String widgetname = bundle.getstring ("name");
  int widgetimage = Bundle.getint ("Itemimage"); if (Intent.getaction (). Equals ("Com.example.yanglh6.myapplication4.staticreceiver")) {View.settextviewtext (
   R.id.widgetname, Widgetname);
   View.setimageviewresource (R.id.widgetimage, widgetimage);
   Appwidgetmanager appwidgetmanager=appwidgetmanager.getinstance (context);

   Appwidgetmanager.updateappwidget (New ComponentName (context, myappwidget.class), view);
   Bitmap bitmap= Bitmapfactory.decoderesource (context.getresources (), Bundle.getint ("Itemimage"));
   int imageID = (int) bundle.get ("Itemimage"); Notificationmanager Notificationmanager = (notificationmanager) context.getsystemservice (Context.NOTIFICATION_ SERVICE);
   Notification.builder Builder = new Notification.builder (context); Builder.setcontenttitle ("static broadcast"). Setcontenttext (bundle.getstring ("name")). Setlargeicon (bitmap). setsmallic
   On (imageID). Setticker ("You have a new message"). Setautocancel (True);

   Intent Intent1 = new Intent (context, mainactivity.class);
   Pendingintent pendingintent = pendingintent.getactivity (context, 0, Intent1, 0);
   Builder.setcontentintent (pendingintent);
   Notification notify = Builder.build ();
  Notificationmanager.notify (0, notify);
 }
 }

Separate the widget part onreceive The rewrite of the method to list:

public void OnReceive (context context, Intent Intent) {
  log.i ("Debug", Intent.tostring ());
  Super.onreceive (context, intent);
  Remoteviews view = new Remoteviews (Context.getpackagename (), r.layout.my_app_widget);
  Bundle Bundle = Intent.getextras ();
  String widgetname = bundle.getstring ("name");
  int widgetimage = Bundle.getint ("Itemimage");
  if (Intent.getaction (). Equals ("Com.example.yanglh6.myapplication4.staticreceiver")) {
   View.settextviewtext ( R.id.widgetname, widgetname);
   View.setimageviewresource (R.id.widgetimage, widgetimage);
   Appwidgetmanager appwidgetmanager=appwidgetmanager.getinstance (context);
   Appwidgetmanager.updateappwidget (New ComponentName (context, myappwidget.class), view);
  }
 

For dynamic registrations, you do not need to add receiver to androidmenifest.xml, but register in dynamicactivity:

 Dynamicreceiver = new Dynamicreceiver ();
     Intentfilter dynamic_filter = new Intentfilter ();
     Dynamic_filter.addaction ("Com.example.yanglh6.myapplication4.dynamicreceiver");
     Registerreceiver (Dynamicreceiver, dynamic_filter);

Therefore, dynamic registration can only be overridden in dynamicreceiver to onreceive functions to complete the update of the widget (similar to static registration):

 @Override public void OnReceive (context context, Intent Intent) {if (Intent.getaction (). Equals ("Com.example.yanglh6.
   Myapplication4.dynamicreceiver ")) {Bundle Bundle = Intent.getextras ();
   Bitmap Bitmap = Bitmapfactory.decoderesource (Context.getresources (), Bundle.getint ("Itemimage"));
   int imageID = Bundle.getint ("Itemimage");
   Remoteviews view = new Remoteviews (Context.getpackagename (), r.layout.my_app_widget);

   String widgetname = bundle.getstring ("name");
   View.settextviewtext (R.id.widgetname, widgetname);
   View.setimageviewresource (R.id.widgetimage, imageID);
   Appwidgetmanager appwidgetmanager=appwidgetmanager.getinstance (context);

   Appwidgetmanager.updateappwidget (New ComponentName (context, myappwidget.class), view); Notificationmanager Notificationmanager = (notificationmanager) context.getsystemservice (Context.NOTIFICATION_
   SERVICE);
   Notification.builder Builder = new Notification.builder (context); Builder.setcontenttitle ("Dynamic Broadcast"). SetconteNttext (Widgetname). Setlargeicon (bitmap). Setsmallicon (imageID). Setticker ("You have a new message"). Setautocancel (t
   Rue);

   Intent mintent = new Intent (context, mainactivity.class);
   Pendingintent pendingintent = pendingintent.getactivity (context, 0, mintent, 0);
   Builder.setcontentintent (pendingintent);
   Notification notify = Builder.build ();
  Notificationmanager.notify (0, notify);
 }
 }

Finish the Experiment ~

Run screenshots

Attention matters

To fully understand the meaning of each part of Androidmenifest.xml and the android mechanism, the Androidmenifest.xml registration and pointing must be clear.

For static, after Sendbroadcast (intent) is implemented, When Androidmenifest.xml finds the receiver of the intent registration and points to the corresponding broadcast receive function, the event is implemented in this function, and for dynamic reasons, the target dynamic broadcast receive class can be defined at that time because of the registration in Dynamicactivity.

SOURCE download

SOURCE Download CLICK here ~

Note

The experimental environment:

Operating System Windows 10
Experimental software Android Studio 2.2.1
Virtual Devices: Galaxy_nexus
Api:21

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.