Android桌面小部件AppWidget

转自:http://blog.csdn.net/zhangphil/article/details/50461944

Android桌面小部件AppWidget(2)

在附录文章1的基础上,我再写一篇关于Android AppWidget的文章,本篇文章实现一个简单功能,此功能亦是对附录文章1所实现功能的增强和改进,本文的代码实现的功能:假设桌面小部件只包含一个Button和一个TextView,当点击Button后,后台启动一个服务(IntentService实现),该服务每个一秒发送一个简单的字符串消息数据data,然后将此消息数据更新到桌面小部件的TextView里面实时显示。
这次,在Androidmanifest.xml有关receiver的定义中,与附录文章1相比,将增加一个action:action_update。本例中,Button的按击事件将触发后台启动服务,后台服务Service每隔一秒制造一个简单字符串数据,然后将此数据实时的以广播形式发给AppWidge,AppWidge收到后,就更新到桌面小部件的TextView里面。

(1)定义AppWidget。

先在Androidmanifest.xml里面定义APP widget的,以Android广播形式:

[html]  view plain  copy
  1. <receiver android:name="zhangphil.widget.AppWidget" >  
  2.             
  3.            <intent-filter>  
  4.                <action android:name="action_button" />  
  5.            </intent-filter>  
  6.              
  7.            <intent-filter>  
  8.                <action android:name="action_update" />  
  9.            </intent-filter>  
  10.              
  11.            <intent-filter>  
  12.                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />  
  13.            </intent-filter>  
  14.   
  15.            <meta-data  
  16.                android:name="android.appwidget.provider"  
  17.                android:resource="@xml/appwidget" />  
  18.              
  19.        </receiver>  

两个用于广播接收的action:action_button和action_update,其中action_button用于在桌面小部件接收用户的点击事件,此action_button将随即启动后台服务,而后台启动的服务将发送广播数据,数据中的广播过滤器即是:action_update。

涉及到的res/xml目录下的appwidget.xml代码文件:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:initialLayout="@layout/appwidget_layout"  
  4.     android:minHeight="20dip"  
  5.     android:minWidth="300dip"  
  6.     android:previewImage="@drawable/ic_launcher"  
  7.     android:resizeMode="horizontal|vertical"  
  8.     android:updatePeriodMillis="0"  
  9.     android:widgetCategory="home_screen" >  
  10.   
  11. </appwidget-provider>  


(2)上次Java代码实现窗口小部件。

核心的AppWidget.java代码:

[java]  view plain  copy
  1. package zhangphil.widget;  
  2.   
  3. import android.app.PendingIntent;  
  4. import android.appwidget.AppWidgetManager;  
  5. import android.appwidget.AppWidgetProvider;  
  6. import android.content.ComponentName;  
  7. import android.content.Context;  
  8. import android.content.Intent;  
  9. import android.util.Log;  
  10. import android.widget.RemoteViews;  
  11.   
  12. public class AppWidget extends AppWidgetProvider {  
  13.   
  14.     @Override  
  15.     public void onReceive(Context context, Intent intent) {  
  16.         super.onReceive(context, intent);  
  17.         Log.d(this.getClass().getName(), "onReceive");  
  18.   
  19.         if (intent == null)  
  20.             return;  
  21.   
  22.         String action = intent.getAction();  
  23.   
  24.         if (action.equals(Constants.ACTION_UPDATE)) {  
  25.             String data = intent.getStringExtra(Constants.KEY_DATA);  
  26.             Log.d(Constants.KEY_DATA, data);  
  27.   
  28.             RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget_layout);  
  29.             remoteViews.setTextViewText(R.id.text, data);  
  30.   
  31.             AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);  
  32.             ComponentName componentName = new ComponentName(context, AppWidget.class);  
  33.             appWidgetManager.updateAppWidget(componentName, remoteViews);  
  34.         }  
  35.   
  36.         // 点击了按钮,开始启动一个后台服务  
  37.         if (action.equals(Constants.ACTION_BUTTON)) {  
  38.             Intent serviceIntent = new Intent(context, MyService.class);  
  39.             context.startService(serviceIntent);  
  40.         }  
  41.     }  
  42.   
  43.     @Override  
  44.     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {  
  45.         Log.d(this.getClass().getName(), "onUpdate");  
  46.   
  47.         Intent intent = new Intent(Constants.ACTION_BUTTON);  
  48.         PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);  
  49.   
  50.         // 小部件在Launcher桌面的布局  
  51.         RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget_layout);  
  52.   
  53.         // 事件  
  54.         remoteViews.setOnClickPendingIntent(R.id.btn, pendingIntent);  
  55.   
  56.         // 更新AppWidget  
  57.         appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);  
  58.     }  
  59.   
  60.     /** 
  61.      * 删除AppWidget 
  62.      */  
  63.     @Override  
  64.     public void onDeleted(Context context, int[] appWidgetIds) {  
  65.         super.onDeleted(context, appWidgetIds);  
  66.         Log.d(this.getClass().getName(), "onDeleted");  
  67.     }  
  68.   
  69.     @Override  
  70.     public void onDisabled(Context context) {  
  71.         super.onDisabled(context);  
  72.         Log.d(this.getClass().getName(), "onDisabled");  
  73.     }  
  74.   
  75.     /** 
  76.      * AppWidget首次创建调用 
  77.      */  
  78.     @Override  
  79.     public void onEnabled(Context context) {  
  80.         super.onEnabled(context);  
  81.         Log.d(this.getClass().getName(), "onEnabled");  
  82.     }  
  83. }  

RemoteViews用到的appwidget_layout.xml,appwidget_layout.xml即是桌面小部件的布局文件:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="horizontal"  
  6.     android:background="#33000000" >  
  7.   
  8.     <Button  
  9.         android:id="@+id/btn"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="启动后台服务" >  
  13.     </Button>  
  14.      
  15.     <TextView  
  16.         android:id="@+id/text"  
  17.         android:text="text"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content" />  
  20.   
  21. </LinearLayout>  

(3)后台服务Service。

MyService.java代码文件,此service是一个Android IntentService,具体实现也可以是Service。此service功能简单,是有桌面小部件的button按钮触发,然后在后台启动,启动后在一个for循环里面循环产生一个简单的字符串数据通过广播形式广播出去,注意打进去的广播过滤器是:action_update。

[java]  view plain  copy
  1. package zhangphil.widget;  
  2.   
  3. import android.app.IntentService;  
  4. import android.content.Intent;  
  5.   
  6. public class MyService extends IntentService {  
  7.   
  8.     private static int ID = 0;  
  9.   
  10.     public MyService() {  
  11.         super("ZhangPhilService");  
  12.     }  
  13.   
  14.     @Override  
  15.     public int onStartCommand(Intent intent, int flags, int startId) {  
  16.         return super.onStartCommand(intent, flags, startId);  
  17.     }  
  18.   
  19.     @Override  
  20.     protected void onHandleIntent(Intent intent) {  
  21.         myLongTimeTask(ID++);  
  22.     }  
  23.   
  24.     private void myLongTimeTask(int id) {  
  25.         for (int i = 0; i < 5; i++) {  
  26.   
  27.             Intent intent = new Intent(Constants.ACTION_UPDATE);  
  28.             intent.putExtra(Constants.KEY_DATA, "Zhang Phil @ CSDN " + id + ":" + i);  
  29.             sendBroadcast(intent);  
  30.   
  31.             try {  
  32.                 Thread.sleep(1000);  
  33.             } catch (InterruptedException e) {  
  34.                 e.printStackTrace();  
  35.             }  
  36.         }  
  37.     }  
  38. }  

记得要将此service注册到Androidmanifest.xml里面:

[html]  view plain  copy
  1. <service android:name="zhangphil.widget.MyService" >  
  2.         </service>  

(4)公共变量的定义(次要)。

因为涉及到众多公共变量的写入和读出,所以定义了一个单独的Constants.java代码类,专门定义公共的变量定义:

[java]  view plain  copy
  1. package zhangphil.widget;  
  2.   
  3. public class Constants {  
  4.     public static final String ACTION_BUTTON = "action_button";  
  5.     public static final String ACTION_UPDATE = "action_update";  
  6.     public static final String KEY_DATA = "data";  
  7. }  

(5)完整的代码结构。

如图所示:



最终,代码运行结果如图所示:


推荐:http://blog.csdn.net/jjwwmlp456/article/details/38466969

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值