Android launcher development (2) appwidget (desktop widget) Analysis

Source: Internet
Author: User

Let's briefly talk about the principle of widgets. Widgets are a piece of information displayed on the desktop. You can also click widgets to jump to a program. The system comes with a program. The typical widget is music. This android built-in music playing applet. This is a typical widget + app application. A program can be started either through a widget or through an app. Widget is an appwidgetprovider + UI interface display (a lot of intent is pre-bound). The information on the interface can be changed through program control. Click the widget and the control on can only send one intent, or send a Service Startup notification. Appwidgetprovider can intercept this intent and process it accordingly (for example, display new information ). In Android development, a large number of XML files need to be configured manually. This is a dream for. NET development. This may also be one of the reasons why General Java programmers are higher than. Net programmers. After all, it is really tiring to do Java Development, especially Android development. You can refer to the source code and explain it against the source code. First, we will develop a simple widget application. The main function we can achieve is to continuously display the current time through constant changes. First, you must manually create a folder named XML. Create an XML file and add the following code:

 <appwidget-providerxmlns:android="http://schemas.android.com/apk/res/android"         android:minHeight="72px"         android:minWidth="72px"         android:updatePeriodMillis="3800000"android:initialLayout="@layout/main">  </appwidget-provider>

This is the display setting of the widget. It is a configuration file for the widget property. Android: minheight indicates the height of the widget, and Android: minwidth indicates the width of the widget. The Android: updateperiodmillis attribute sets the Update Time Frequency of the widget page. The Android: initiallayout attribute indicates the layout of the initialization page. The UI is painted in Android through XML files or code programs, however, this painting is too troublesome. Check the following file system. The res folder is the directory where the system stores resource files. A folder starting with drawable is a folder that stores image resources. The subsequent hdpi and ldpi are usually used to call different image resources in different states, such as landscape and landscape. Layout stores XML, and the uidesign is in this layout folder. Strings. xml put in value is a string separated from the program, which may be used for internationalization.
Look at main. XML in layout. Only one space is textview, which is used to display the time. The testappwidget class inherits from appwidgetprovider, while appwidgetprovider inherits from Android. content. broadcastreceiver. Therefore, testappwidget is the broadcastreceiver that intercepts intent. These intents can only be set in androidmainfest to intercept processing.

Public class testappwidget extends appwidgetprovider {Private Static final string tag = "testappwidget"; Private Static final string fresh = "com. sinxiao. app. fresh "; private context mcontext; private Boolean run = true; broadcastreceiver mbroadcast = newbroadcastreceiver () {public void onreceive (contextcontext, intent) {string action = intent. getaction (); If (action. equals (intent. action_time_tick) {mcontext. sendbroadcast (newintent (FRESH) ;}};/*** notify the widget to refresh every 1 second */thread mythread = new thread () {public void run () {While (run) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} mcontext. sendbroadcast (newintent (FRESH); // intent of the notification refresh widget };}; @ override public void onupdate (contextcontext, appwidgetmanager, int [] appwidgetids) {// used to display the log on the widget refresh interface. D (TAG, "onupdate"); super. onupdate (context, appwidgetmanager, appwidgetids); mcontext = context; remoteviews views = newremoteviews (context. getpackagename (), R. layout. main); Calendar Cal = calendar. getinstance (); system. out. println (Cal. gettime (). tolocalestring (); views.settextviewtext(r.id.txt Tim, Cal. gettime (). tolocalestring (); appwidgetmanager. updateappwidget (appwidgetids, views); mythread. start ();/*** this class can be used as a bracastreveiver to register a listener (you can cancel comments and see what errors are reported) * // context. registerreceiver (mbroadcast, new intentfilter (intent. action_time_tick);} @ override public void onreceive (contextcontext, intent) {log. D (TAG, "onreceive"); string action = intent. getaction (); log. D (TAG, "theaction is" + action); If (fresh. equals (Action) {Showtime (context);} elseif (intent. action_time_tick.equals (Action) {Showtime (context);} super. onreceive (context, intent);} private void Showtime (contextcontext) {remoteviews views = newremoteviews (context. getpackagename (), R. layout. main); Calendar Cal = calendar. getinstance (); views.settextviewtext(r.id.txt Tim, Cal. gettime (). tolocalestring (); componentname thiswidget = new componentname (context, testappwidget. class); appwidgetmanager. getinstance (context ). updateappwidget (thiswidget, views);} public void ondisabled (contextcontext) {log. D (TAG, "ondisabled"); super. ondisabled (context); run = false ;}}

The above code is the main program used to change the display time and process and refreshintent. Check how fresh intent is bound to the testappwidget in androidmainifest. Check that there is a <action Android: Name = "com. sinxiao. app. fresh "/> indicates the intent to intercept. The onreceive () method in the parent class is overwritten in the main program.

        private static final StringFRESH="com.sinxiao.app.fresh";public void onReceive(Contextcontext, Intent intent) {String action=intent.getAction();Log.d(tag, "theaction is "+action);if (FRESH.equals(action)){showTime(context);}elseif(Inent.ACTION_TIME_TICK.equals(action)){showTime(context);}super.onReceive(context,intent);}

The fresh displays the fresh intent bound to us.
 

<? XML version = "1.0" encoding = "UTF-8"?> <Manifestxmlns: Android = "http://schemas.android.com/apk/res/android" package = "com. sinxiao. widgetapp "Android: versioncode =" 1 "Android: versionname =" 1.0.0 "> <applicationandroid: icon =" @ drawable/icon "Android: label = "@ string/app_name"> <Cycler Android: Name = ". setting. testappwidget "> <intent-filter> <actionandroid: Name =" android. appwidget. action. appwidget_update "/> <! -- This intent does not support registration in the configuration file, so it is useless. --> <! -- <Actionandroid: Name = "android. Intent. Action. time_tick"/> --> </intent-filter> <! -- Manually configure intentaction on the mainset file --> <action Android: Name = "com. sinxiao. app. fresh "/> </intent-filter> <meta-data Android: Name =" android. appwidget. provider "Android: Resource =" @ XML/testwidget_setting "/> </receiver> </Application> </manifest>

This is a simple implementation of widgets. It should be noted that there are many hidden rules in the android widgets. If you are not careful, you may be tempted. This shows that practice is the only criterion for testing truth. How do I assign values to widgets? As follows:
 

 RemoteViews views = newRemoteViews(context.getPackageName(),R.layout.main);   Calendar    cal=Calendar.getInstance();    System.out.println(cal.getTime().toLocaleString());    views.setTextViewText(R.id.txttim,cal.getTime().toLocaleString());        appWidgetManager.updateAppWidget(appWidgetIds,views);

Why does remoteviews need to be used to set the interface for the Widget? I don't know. What can the senior man tell me? This is a potential rule. In general apps, setcontentview (R. layout. Main); is used directly. This remoteviews is more special. When setting text, you must use views.settextviewtext(r.id.txt Tim, Cal. gettime (). tolocalestring (). This abnormal method can assign values, which is hard to understand. Appwidgetmanager updates the page and refreshes the widget interface. After obtaining the action
When the value is the intent of COM. sinxiao. App. Fresh, the page is also updated. In the Showtime (); method,

    ComponentName thisWidget = new ComponentName(context,TestAppWidget.class);    AppWidgetManager.getInstance(context).updateAppWidget(thisWidget,views);

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.