Android UI Components Appwidget controls Getting started with a detailed _android

Source: Internet
Author: User

Widget Introduction

We can understand widgets as a widget (pendant) placed on the desktop, and we can easily do a variety of things directly on the desktop, such as playing music.

When we press the desktop long, we can see the widget option, as shown in the following illustration:


Clicking the Widgets icon in the arrow above shows the following interface: (All widgets)

Long Press any widget in the image above to put it on the desktop.

Use of Widgets
The realization idea of widget
(1) Declaring appwidget in the androidmanifest;
(2) Define the Appwidget configuration file in the XML directory;
(3) The layout file of the widget is defined in the layout directory;
(4) Create a new class, inherit the Appwidgetprovider class, and implement the specific widget business logic.

We need to create a new class that inherits Appwidgetprovider. Point open Appwidgetprovider, found Appwidgetprovider unexpectedly is inherited from Broadcastreceiver.

Why is a widget a broadcast receiver? We know that there is a OnReceive method in the Broadcastreceiver class to receive broadcasts. When we are on the desktop pendant to do the operation, will inevitably cause the application of the change, which involves the communication between the pendant and the application, at this time to communicate with the radio is better.

the specific steps of using the widget

(1) Create a new class Testwidget.java, inherit Appwidgetprovider:
Testwidget.java:

Import Android.appwidget.AppWidgetProvider;
Import Android.content.Context;
Import android.content.Intent;
/**
 * Created by smyhvae on 2016/9/7.
 *
/public class Testwidget extends appwidgetprovider{
 @Override
 the public void onreceive Intent Intent) {
  super.onreceive (context, Intent);
 }
} 

(2) because the widget is a broadcast receiver, we need to register in the manifest file:

 <!--declare widget corresponding to Appwidgetprovider-->
  <receiver android:name= ". Testwidget ">
   <intent-filter>
    <action android:name=" android.appwidget.action.APPWIDGET_ UPDATE "/>
   </intent-filter>
   <meta-data
    android:name=" Android.appwidget.provider "
    android:resource= "@layout/widget_setting"/>
  </receiver> 

Line 04: Action is a filtering condition used to filter the behavior and monitor widget updates.
Line 08: android:resource Specifies the configuration of the widget. As we know, attributes are used to store data in the manifest file.

(3) New file in Layout folder Widget_setting.xml: (Widget's configuration file)
Setting_widget.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <appwidget-provider xmlns:android=
"http://schemas.android.com" /apk/res/android "
     android:layout_width=" match_parent "
     android:layout_height=" Match_parent "
     Android : initiallayout= "@layout/layout_widget"
     android:minheight= "140DP"
     android:minwidth= "140DP"
     android: Previewimage= "@mipmap/ic_launcher"
     android:updateperiodmillis= "20000"
     android:widgetcategory= "home_ Screen "
 >
</appwidget-provider> 

Line 08: android:initiallayout Specifies the layout of the widget.
09 lines: Android:updateperiodmillis Specify the time period for the update
Line 10: android:widgetcategory= "Home_screen" displays the widget on the main screen (or on the lock screen)

(4) New file in Layout folder Layout_widget.xml: (Widget layout)
Layout_widget.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
    android:layout_width=" match_parent "
    android:layout_height=" match_parent "
    android:o" rientation= "vertical" >
 <textview
  android:id= "@+id/textview" android:layout_width= "WRAP_"
  Content "
  android:layout_height=" wrap_content "
  android:layout_gravity=" Center_horizontal "
  android: text= "Large Text"
  android:textappearance= "Android:attr/textappearancelarge"/>
 <button
  Android:id= "@+id/button2"
  android:layout_width= "wrap_content"
  android:layout_height= "Wrap_content"
  android:layout_gravity= "Center_horizontal"
  android:text= "New button"/>
</LinearLayout> 

So the program can run. After running the program, long press the desktop, click on the "widget" button, you can see that we have just designed the widget:


By following the arrows in the image above, you can drag and drop the widget we have designed to the desktop:


widget clicks and Updates "important"

We know that Testwidget.java inherits from Appwidgetprovider, and Appwidgetprovider overrides the OnReceive method after inheriting Broadcastreceiver, and then also customizes many methods:


The above illustration contains various methods such as when it is deleted, when it is forbidden, when it is enabled, and when it is updated. Of particular importance are the OnReceive () method and the OnUpdate () method.
When the widget is changed (for example, it is installed on the desktop), an updated broadcast is sent (shown in the Red box section above). We set the update frequency of the widget in the Setting_widget.xml, which also invokes the update.

Some people may ask, after my boot, the weather and other widgets why not update it? This is because the process is killed, then we can only remove the control first, and then install it, the application will send update updates of the broadcast.

When you need to do widgets Click and update, we need to rewrite the OnUpdate () method to send the broadcast. When the program initializes, the system calls the OnUpdate () method.

The code in the OnUpdate () method is as follows:

 @Override public void OnUpdate (context context, Appwidgetmanager Appwidgetmanager, in
  T[] appwidgetids) {super.onupdate (context, Appwidgetmanager, appwidgetids);
  Remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.layout_widget);//need to construct a RemoteViews
  Intent Intent = new Intent (); Intent.setclass (context, testwidget.class); The broadcast is sent to the testwidget itself via intent, and Testwidget is invoked after receiving the broadcast.
  And then refresh the reference//.
  Intent.setaction (widget_btn_action);
  Pendingintent pendingintent = pendingintent.getbroadcast (context, 0, intent, 0);
  Remoteviews.setonclickpendingintent (R.ID.WIDGET_BTN, pendingintent);//Control Btn_widget Click event: When the button is clicked, a broadcast with an action is sent. Appwidgetmanager.updateappwidget (Appwidgetids, remoteviews);
 After clicking, remember to update. } 

Code Explanation:
First you need a new remoteviews, the construction method needs to pass two parameters, one is the package name (Context.getpacakgename), and the other is the layout file (layout_widget).
Then set the Click event of the button via Remoteviews.setonclickpendingintent (). Setonclickpendingintent () needs to pass two parameters: one is the ID (for example, button that needs to be clicked), one is pendingintent. Pendingintent is the intention of the future.
So we need to construct a pendingintent beforehand, which needs to be constructed by Pendingintent.getbroadcast (). Four parameters need to be passed in the Getbroadcast () method, one of which is intent.
So we need to construct a intent. Send a broadcast in the intent and set the action.
button after clicking, Remember to call Appwidgetmanager.updateappwidget (int[] appwidgetids, remoteviews views) method Update, the first parameter is the OnUpdate method in the parameters, Represents all of the controls.

After broadcasting the button hit time by intent in the OnUpdate () method, we need to receive the broadcast in the OnReceive () method.
The code in the OnReceive () method is as follows:

 @Override public void OnReceive (context context, Intent Intent) {super.onreceive (CO
  ntext, intent); if (intent!= null && textutils.equals (Intent.getaction (), widget_btn_action)) {//When the intent is not empty and the ACTION match succeeds,
   Receive the broadcast, then click on the event Success LOG.I (Widget_btn_action, "is clicked"); The next step is to do the contents of the Click event remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.layout_widget);
   Note: "Re" constructs a remoteviews remoteviews.settextviewtext (R.ID.WIDGET_TV, "be clicked");
   Remoteviews.settextcolor (R.ID.WIDGET_TV, color.red); Appwidgetmanager Appwidgetmanager = appwidgetmanager.getinstance (context);//single case mode componentname componentname = new Com
   Ponentname (context, testwidget.class); Appwidgetmanager.updateappwidget (ComponentName, remoteviews); After//settext, remember to update}} 

Code Explanation:
When the intent action match succeeds, start to perform the settext after the click Time, but there is a need to recreate a remoteviews, instead of sharing the remoteviews in the OnUpdate (which is a big hole).
After performing the SetText after the Click event, remember to call Appwidgetmanager.updateappwidget (ComponentName, Remoteviews) method, the first parameter is the component name, we need to new, The second parameter is well explained.

In combination, the full version of the Testwidget.java code is as follows:
Testwidget.java:

 Import android.app.PendingIntent;
Import Android.appwidget.AppWidgetManager;
Import Android.appwidget.AppWidgetProvider;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import Android.graphics.Color;
Import Android.text.TextUtils;
Import Android.util.Log;
Import Android.widget.RemoteViews;
 /** * Created by smyhvae on 2016/9/7. * * public class Testwidget extends Appwidgetprovider {public static final String widget_btn_action = "Widget_btn_action"
 ;
  @Override public void OnReceive (context, Intent Intent) {super.onreceive (context, Intent); if (intent!= null && textutils.equals (Intent.getaction (), widget_btn_action)) {//When the intent is not empty and the ACTION match succeeds,
   Receive the broadcast, then click on the event Success LOG.I (Widget_btn_action, "is clicked"); The next step is to do the contents of the Click event remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.layout_widget);
   Note: "Re" constructs a remoteviews remoteviews.settextviewtext (R.ID.WIDGET_TV, "be clicked"); RemOteviews.settextcolor (R.ID.WIDGET_TV, color.red); Appwidgetmanager Appwidgetmanager = appwidgetmanager.getinstance (context);//single case mode componentname componentname = new Com
   Ponentname (context, testwidget.class); Appwidgetmanager.updateappwidget (ComponentName, remoteviews); After//settext, remember to update} @Override public void OnUpdate (Co ntext context, Appwidgetmanager Appwidgetmanager, int[] appwidgetids) {super.onupdate-context, Appwidgetmanager, appWi
  Dgetids);
  Remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.layout_widget);//need to construct a RemoteViews
  Intent Intent = new Intent (); Intent.setclass (context, testwidget.class); The broadcast is sent to the testwidget itself via intent, and Testwidget is invoked after receiving the broadcast.
  And then refresh the reference//.
  Intent.setaction (widget_btn_action);
  Pendingintent pendingintent = pendingintent.getbroadcast (context, 0, intent, 0);
  Remoteviews.setonclickpendingintent (R.ID.WIDGET_BTN, pendingintent);//Control Btn_widget Click event: When the button is clicked, a broadcast with an action is sent. Appwidgetmanager.updateappwidget (APPWIDgetids, remoteviews);
 After clicking, remember to update. 
 }
}

After running, drag the widget onto the desktop with the following effect:

After clicking the button, the effect is as follows:

Project Documentation: (Android Studio 2.1)

Of course, there are many other uses for widgets. Like what:
• Communication with Service
The interaction method of the widget control.
• How to make a desktop player widget

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.