Android AppWidget开发不同于普通的android应用,因为AppWidget是运行在别的进程中的程序。其使用RemoteViews更新UI。一旦系统发生变更,很容易引起AppWidget的更新。其支持的组件有限,事件类型也很少。所以一般用于更新周期较长,事件比较简单的用于桌面显示的组件。其开发流程相对来说还是比较简单的。大致分为:
1:编写布局文件
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:text="Starting..." android:textColor="#FFFF00" android:textSize="14dip" />
2:编写Provider配置文件和Manifest配置文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mywidget" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name="MyTime" android:label="MyTime"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/my_time" /> </receiver> <service android:name="MyTime$MyService" /> </application> </manifest>
3:编写业务逻辑
package com.mywidget; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.app.Service; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; public class MyTime extends AppWidgetProvider { Timer timer; Context context; // onUpdate @Override public void onUpdate(Context con, AppWidgetManager appWidgetManager, int[] appWidgetIds) { context = con; timer = new Timer(); timer.schedule(timertask, 0, 1000);//1秒钟调用一次 } // MyService服务程序 public static class MyService extends Service { @Override public void onStart(Intent intent, int startId) { RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_time);//设置显示控件 remoteViews.setTextViewText(R.id.TextView01, new Date().toLocaleString()); ComponentName thisWidget = new ComponentName(this, MyTime.class); AppWidgetManager manager = AppWidgetManager.getInstance(this); manager.updateAppWidget(thisWidget, remoteViews); } @Override public IBinder onBind(Intent intent) { return null; } }; // Handler private Handler handler = new Handler() { public void handleMessage(Message msg) { Intent intent = new Intent(context, MyService.class); context.startService(intent); } }; private TimerTask timertask = new TimerTask() { public void run() { Message message = new Message(); handler.sendMessage(message); } }; }
喜欢的朋友关注我!
版权声明:本文为博主原创文章,未经博主允许不得转载。
Android实战简易教程-第六十八枪(android小工具appwidget之时间显示)
原文地址:http://blog.csdn.net/yayun0516/article/details/49487833