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:

To establish the file Example_appwidget_info.xml in the XML directory under the resource file:

<?xml version= "1.0" encoding= "Utf-8"?

><appwidget-provider xmlns:android= "Http://schemas.android.com/apk/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 The events in our application that show the desktop application on different desktops of their widgets created and destroyed corresponding callbacks may not be available * 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 run 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 runs 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, run ondisable (). Stop the service we opened//delete the junk file temporary 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 corresponding widget view of Jinshan mobile phone defender , only for reference:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ 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>
Effect:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvew9uz2jpbmdjagfv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>

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 Android.app.pendingintent;import Android.app.service;import Android.appwidget.appwidgetmanager;import Android.content.componentname;import Android.content.intent;import Android.graphics.color;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 (r.id.process_count, "XXXX");//Set Text Views.settextcolor for Process_count ( R.id.process_count, color.red);//Set text color views.settextviewtext for Process_count (r.id.process_memory, "XXXX"); Views.settextcolor (R.id.process_memory, color.red); Intent Intent = new Intent (updatewidgetservice.this, Xxxx.class); Pendingintent pendingintent = Pendingintent.getbroadcast (Getapplicationcontext (), 0, intent, 0); Views.setonclickpendingintent (R.id.btn_clear, 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 ();}}

Use of Android Appwidget and timing updates for widgets with TimerTask

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.