The use of Android Appwidget and the use of TimerTask to implement widget timing updates

Source: Internet
Author: User

The first step: first, the definition declaration of the widget:

Create the file Example_appwidget_info.xml in the XML folder under the resource file:

<?xml version= "1.0" encoding= "Utf-8"? ><appwidget-provider xmlns:android= " Res/android "    android:initiallayout=" @layout/process_widget "    android:minheight=" 72.0dip "    android: Minwidth= "294.0dip"    android:updateperiodmillis= "0"/>

Step Two: Write Mywidget class implementation Appwidgetprovider

Package Cn.itcast.testwidget;import Cn.itcast.mobilesafe.service.updatewidgetservice;import Android.appwidget.appwidgetmanager;import Android.appwidget.appwidgetprovider;import Android.content.Context; Import android.content.intent;/** * Update the interface minimum for half an hour based on the profile every fixed time 1800000 ms Onrecevie-> OnUpdate Note * Widget This component is not real In our application there are different desktop applications displayed on the desktop of their widgets created and destroyed corresponding callback events may have no * Android LUNCHER/HTC sence/M ui/360 desktop/AWT/QQ Desktop/... */pu Blic class Mywidget extends Appwidgetprovider {//Appwidgetprovider inherited from Broadcastreceiver@Overridepublic void OnReceive (context context, Intent Intent) {//TODO auto-generated method Stubsuper.onreceive ( context, intent); System.out.println ("OnReceive");} @Overridepublic void OnUpdate (context context, Appwidgetmanager appwidgetmanager,int[] appwidgetids) { System.out.println ("OnUpdate"); Super.onupdate (context, Appwidgetmanager, appwidgetids);} @Overridepublic void ondeleted (context context, int[] appwidgetids) {super.ondeleted (context, appwidgetids);// The OnDelete method is executed when a widget is deleted Intent = new Intent (context, updatewidgetservice.class); Context.stopservice (Intent);} @Overridepublic void onenabled (context context) {super.onenabled (context);//The method that the widget executes when it is first created//initializes the operation of the widget data, Open background service, etc. Intent = new Intent (context, updatewidgetservice.class); Context.startservice (Intent);} @Overridepublic void ondisabled (context context) {super.ondisabled (context); System.out.println ("ondisabled");//When all widgets are deleted execute ondisable ();//Stop our Open service//delete junk file temp file}}
Step three: Register the activity in the manifest file:

<receiver android:name= "Mywidget" >    <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>

Fourth: Create a View resource file for the widget:

The following is the Golden Hill Mobile defender's widget view, for reference only:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= " Android "Android:layout_width=" Fill_parent "android:layout_height=" wrap_content "android:gravity=" center_vertical "Android:src=" @drawable/widget_bg_portrait "> <linearlayout android:id=" @+id/pw_ll "Android:lay Out_width= "0.0dip" android:layout_height= "fill_parent" android:layout_marginleft= "5.0dip" Android:lay        Out_weight= "1.0" android:background= "@drawable/widget_bg_portrait_child" android:gravity= "center_vertical"        android:orientation= "vertical" android:paddingbottom= "3.0dip" android:paddingtop= "3.0dip" > <textview android:id= "@+id/process_count" android:layout_width= "Wrap_content" Android: layout_height= "Wrap_content" android:layout_marginleft= "10.0dip"/> <imageview android:         Layout_width= "Fill_parent"   android:layout_height= "Wrap_content" android:layout_marginbottom= "1.0dip" Android:layout_marginto            p= "1.0dip" android:background= "@drawable/widget_bg_portrait_child_divider"/> <textview Android:id= "@+id/process_memory" android:layout_width= "wrap_content" android:layout_height= "Wrap_co Ntent "android:layout_marginleft=" 10.0dip "/> </LinearLayout> <linearlayout Android:la Yout_width= "Wrap_content" android:layout_height= "wrap_content" android:gravity= "Center_horizontal" an droid:orientation= "vertical" > <linearlayout android:layout_width= "wrap_content" Androi d:layout_height= "Wrap_content" android:gravity= "center_vertical" > <imageview A Ndroid:layout_width= "20.0dip" android:layout_height= "20.0dip" android:background= "@drawable/     Notification "/>       <textview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "@string/app_name"/> </LinearLayout> <button Android:id = "@+id/btn_clear" android:layout_width= "90.0dip" android:layout_height= "Wrap_content" and Roid:layout_centervertical= "true" android:layout_margintop= "5.0dip" android:background= "@drawable/bu Tton_background_selected "android:text=" one-click Cleanup "/> </LinearLayout></LinearLayout>

Fifth: Regularly update views with Updatewidgetservice services:

Package Cn.itcast.mobilesafe.service;import Java.util.timer;import Java.util.timertask;import Cn.itcast.mobilesafe.r;import Cn.itcast.mobilesafe.receiver.lockscreenreceiver;import Cn.itcast.mobilesafe.ui.taskmanageractivity;import Cn.itcast.mobilesafe.util.taskutil;import;import;import Android.appwidget.appwidgetmanager;import Android.content.componentname;import Android.content.intent;import;import Android.os.ibinder;import Android.widget.remoteviews;public class Updatewidgetservice extends Service {private Timer Timer;private timertask task;private appwidgetmanager widgetmanager; @Overridepublic ibinder onbind (Intent Intent) { return null;} @Overridepublic void OnCreate () {timer = new timer (); Widgetmanager = Appwidgetmanager.getinstance ( Getapplicationcontext ()); task = new TimerTask () {@Overridepublic void Run () {//Update widget interface componentname name = new Compon Entname ("Cn.itcast.mobilesafe", "CN.ITCAST.MOBILESAFE.RECEIVER.PRocesswidget ");//get widgetremoteviews views = new Remoteviews (" Cn.itcast.mobilesafe ", R.layout.process_ Widget),//Get widget layout views.settextviewtext (, "XXXX");//Set Text Views.settextcolor for Process_count (,;//Set text color views.settextviewtext for Process_count (, "XXXX"); Views.settextcolor (,; Intent Intent = new Intent (updatewidgetservice.this, Xxxx.class); Pendingintent pendingintent = Pendingintent.getbroadcast (Getapplicationcontext (), 0, intent, 0); Views.setonclickpendingintent (, pendingintent);//To Btn_ in the layout file Clear Set Click event Widgetmanager.updateappwidget (name, views);//Update widget}};timer.scheduleatfixedrate (Task, 1000, 2000);// Delay one second update frequency 2 seconds super.oncreate ();} @Overridepublic void OnDestroy () {timer.cancel (); timer = Null;task = Null;super.ondestroy ();}}

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: 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.