First, the Android app widget introduction
App widgets are application widgets (widgets) that are miniature application views that can be embedded in other applications (such as desktops) and receive periodic updates.
First of all, let's take a look at the effect of the picture.
Widget widgets, which usually have some functionality and are usually associated with an application, trigger the corresponding application by tapping the widget widget on the phone's desktop. Widget widgets, which usually require the user to manually display their own mobile desktop (long press the phone desktop, add "Widgets", from the small parts list).
Many app apps bring widgets, such as "listening to music" from QQ. Installed friends, long press the phone desktop, add "Widgets", you will find the widget list will have QQ music "listening to the song."
For more information, refer to the official Android text
Second, the Widget related class introduction1, Appwidgetprovider class
Appwidgetprovider inherits from Broadcastreceiver, which can receive widget-related broadcasts, such as update, delete, open, and disable widgets. Our Android app can publish a widget via a appwidgetprovider.
Usually our Android application needs to define a class that inherits Appwidgetprovider.
Broadcast processing functions in the Appwidgetprovider
(1) onUpdate ()
Executed when the widget is updated. Similarly, when a user first adds a widget, OnUpdate () is also called so that the widget can do the necessary setup work, if needed. However, if you define the Configure property of the widget (that is, Android:config, which is described later), onUpdate () will not be called when the user first adds the widget, and OnUpdate will not be called until the widget is updated.
(2) onappwidgetoptionschanged ()
Onappwidgetoptionschanged () is executed when the widget is first added or when the widget size is changed. In this function, you can show/hide some content based on the size of the widget. The bundle object can be returned by getappwidgetoptions () to read the widget's size information, including the following information in the bundle:
option_appwidget_min_width– contains the lower bound of the widget's current width, in DP units.
The option_appwidget_min_height– contains the lower bound of the widget's current height, in DP units.
option_appwidget_max_width– contains the upper limit of the widget's current width, in DP units.
option_appwidget_max_height– contains the upper limit of the widget's current height, in DP units.
Onappwidgetoptionschanged () was introduced by Android 4.1.
(3) ondeleted (Context, int[])
Triggered when the widget is deleted.
(4) onenabled (Context)
Triggered when an instance of the 1th widget is created. That is, if the user has added two times (two instances) to the same widget, then onenabled () will only be triggered when the widget is added for the first time.
(5) ondisabled (Context)
Triggered when an instance of the last 1 widgets is deleted.
(6) onreceive (Context, Intent)
Triggered when any broadcast is received, and is called before the method described above.
In summary, Appwidgetprovider inherits from Broadcastreceiver. In fact, methods such as OnUpdate (), onenabled (), ondisabled () in App Widge are distributed in OnReceive () and are onreceive () responses to specific events.
2, Appwidgetproviderinfo
Appwidgetproviderinfo describes an app widget metadata, such as the layout of the app widget, the update frequency, and the Appwidgetprovider class, which is defined in res/xml with the suffix XML. The following XML example describes the types that are commonly used in appwidgetproviderinfo.
<!--? XML version= "1.0" encoding= "Utf-8"?--> <!-- android:minwidth: Min. width android:minheight: Min. height android:updateperiodmillis: Update widget time interval (ms), "86400000" for 1 hours android:previewimage: Preview picture Android:initiallayout: The corresponding layout file Android:resizeMode:widget can be stretched in the direction of loading to the desktop. Horizontal indicates that you can stretch horizontally, and vertical indicates where the android:widgetCategory:widget can be displayed vertically. Home_screen indicates that widgets can be added to the desktop, keyguard that widgets can be added to the lock screen. android:initialkeyguardlayout: Layout file when loading to lock screen-- </appwidget-provider>
(1) Updateperiodmillis
It defines how often the widget is updated. The actual timing of the update is not necessarily exactly what happens at this time. Recommended updates try not to be too frequent, preferably less than 1 hours at a time. Alternatively, you can configure the Activity to allow users to configure the update frequency. In fact, when the value of Updateperiodmillis is less than 30 minutes, the system automatically sets the update frequency to 30 minutes! This section will be described in more detail later.
Note: When the update time arrives, if the device is hibernating, the device will be woken up to perform the update. If the update frequency does not exceed 1 hours at a time, then the battery life should not have a lot of impact. If you need more frequent updates, or if you don't want to perform updates while your device is hibernating, you can use alarm-based updates instead of the widget's own refresh mechanism. Setting the alarm type to elapsed_realtime or RTC will not wake the dormant device, and set the Updateperiodmillis to 0.
Therefore, if we update the widget's component dynamically, it is best to use the service, Alarmmanager, timer and so on.
(2) Initiallayout
The layout resource file that points to the widget
(3) Widgetcategory
Specifies where the widget can be displayed: whether it can be displayed in home screen or lock screens or both. Its values include: "Home_screen" and "Keyguard". Android 4.2 introduced.
Third, the use of the widget procedures for the overall widget program, need to modify three XML files, a class file:
1. The first XML is a layout XML file (such as: Res\layout\my_time_widget.xml), which is the interface of this widget. In general, if you use this widget to display time, just declare a textview in this layout XML.
2. The second XML is Res\xml\my_time_widget_info.xml, which is used primarily to declare a appwidget. Layout is the designation of the my_time_widget.xml above.
3. The third XML is androidmanifest.xml, which registers the broadcastreceiver information. android: name=". Mytimewidget ", Mytimewidget is a custom Java class that inherits from Appwidgetprovider.
4. The last class is used to do some business logic operations. Create a new Mytimewidget class to inherit the class Appwidgetprovider. There are many callback methods in Appwidgetprovider.
Instance:
1. Widget Interface Layout Res\layout\my_time_widget.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "match_parent "Android:layout_height=" match_parent "android:background=" #09C "android:padding=" @dimen/widget_margin "> &L T TextView android:id= "@+id/appwidget_text" android:layout_width= "Wrap_content" android:layout_height= " Wrap_content "android:background=" #09C "android:contentdescription=" @string/appwidget_text "android:t ext= "@string/appwidget_text" android:textcolor= "#ffffff" android:textsize= "24sp" android:textstyle= "b Old|italic "android:layout_marginleft=" 8DP "android:layout_marginright=" 8DP "android:layout_margintop = "106DP" android:layout_alignparenttop= "true" android:layout_centerhorizontal= "true"/> <textclock Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/ap Pwidget_text "Android:Layout_centerhorizontal= "true" android:id= "@+id/textclock"/></relativelayout>
Layout file: Contains aTextView is used to display time, and aTextclock.
2. Widget description File Res\xml\my_time_widget_info.xml
<?xml version= "1.0" encoding= "Utf-8"? ><appwidget-provider xmlns:android= "http://schemas.android.com/apk/ Res/android " android:initialkeyguardlayout=" @layout/my_time_widget " android:initiallayout=" @layout/my_ Time_widget " android:minheight=" 110DP " android:minwidth=" 250DP " android:previewimage=" @drawable/ Example_appwidget_preview " android:resizemode=" horizontal|vertical " android:updateperiodmillis=" 86400000 " android:widgetcategory=" Home_screen "></appwidget-provider>
3. manifest file Androidmanifest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.ljheee.mytimewidget "> <application android:allowbackup=" true "Android:icon = "@mipmap/ic_launcher" android:label= "@string/app_name" android:supportsrtl= "true" Android:theme= "@st Yle/apptheme "> <receiver android:name=". Mytimewidget "> <intent-filter> <action android:name=" Android.appwidget.action.APPWID Get_update "/> <action android:name=" Com.ljheee.widget.UPDATE_TIME "/> </intent-filte r> <meta-data android:name= "Android.appwidget.provider" android:resource= "@ Xml/my_time_widget_info "/> </receiver> <service android:name=". Timeservice "android:enabled=" true "android:exported=" true "> <intent-filter> <action android:name= "Android.appwidget.action.MY_APP_WIDGET_SERVICE"/> </intent-filter> </service> </application></manifest>
4, Mytimewidget.java
Package Com.ljheee.mytimewidget;import Android.appwidget.appwidgetmanager;import Android.appwidget.appwidgetprovider;import Android.content.componentname;import Android.content.Context;import Android.content.intent;import Android.os.asynctask;import Android.widget.remoteviews;import Java.text.simpledateformat;import Java.util.date;public class Mytimewidget extends Appwidgetprovider {static SimpleDa Teformat SDF = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); Start the Exampleappwidgetservice service corresponding to the action private final Intent time_service_intent = new Intent ("Android.appwi Dget.action.MY_APP_WIDGET_SERVICE "); Update the widget's broadcast corresponding to the ACTION private final String Action_update_all = "Com.ljheee.widget.UPDATE_TIME"; Context Mcontext; GetDate GetDate; static void Updateappwidget (context context, Appwidgetmanager Appwidgetmanager, int appwidg Etid) {Charsequence Widgettext = context.getstring (R.string.appwidget_text); ConstrUCT the Remoteviews object remoteviews views = new Remoteviews (Context.getpackagename (), r.layout.my_time_widget); Views.settextviewtext (R.id.appwidget_text, Sdf.format (New Date ())); Instruct the Widget Manager to update the widgets Appwidgetmanager.updateappwidget (Appwidgetid, views); } @Override public void OnReceive (context context, Intent Intent) {if (mcontext==null) {Mcontext = Context Final String action = Intent.getaction (); if (Action_update_all.equals (ACTION)) {//"update" Broadcast//Updateappwidget (context, Appwidgetmanager.getins Tance (context));//OnUpdate (context,appwidgetmanager.getinstance (context), mappwidgetids); GetDate = new GetDate (); Getdate.execute (); } super.onreceive (context, intent); } @Override public void OnUpdate (context context, Appwidgetmanager Appwidgetmanager, int[] appwidgetids) {// There may multIple widgets Active, so update all of the them for (int appwidgetid:appwidgetids) {Updateappwidget (Contex T, Appwidgetmanager, Appwidgetid); }} @Override public void onenabled (context context) {//Opens the service when the first widget is created Context.startservic E (time_service_intent); super.onenabled (context); } @Override public void ondisabled (context context) {//Terminates service Context.stopservice when the last widget is deleted (TI Me_service_intent); super.ondisabled (context); }//Request data Class GetDate extends Asynctask {Appwidgetmanager AWM = null; ComponentName componentname = null; @Override protected void OnPreExecute () {if (awm==null) {AWM = Appwidgetmanager.getinstan CE (mcontext); } if (componentname==null) {componentname = new ComponentName (Mcontext, Appwidgetprovider.class); } super.onpreexecute (); } @OverridE protected Object doinbackground (object[] params) {return null; } @Override protected void OnPostExecute (Object o) {//update interface Remoteviews remoteviews = New Remoteviews (Mcontext.getpackagename (), r.layout.my_time_widget); Remoteviews.settextviewtext (R.id.appwidget_text, Sdf.format (New Date ())); Awm.updateappwidget (ComponentName, remoteviews); Super.onpostexecute (o); } }}
Currently Android Studio 2.23 version, directly create a new Android project (No Activity), in the empty project, directly New-àwidget-àapp widgets. Enter the Mytimewidget class name, the related widget interface layout, widget description file, manifest file registration integration automatically built.
compile and run the program, we know that the widget program, even if it is finished will not appear in the program list, because it does not have main Activity, long press on the desktop, wait for the pop-up dialog box, select "Widget", from the list select drag and drop with the mobile phone desktop.
Complete project: Https://github.com/ljheee/MyTimeWidget
----Full parsing of Android widget widgets