桌面部件是一种利用AppWidget框架将应用程序的某个部件放在桌面。
class="magplus" title="点击查看原始大小图片" src="/Upload/Images/2015012114/93476D486F732BB6.jpg" alt="" width="700" height="494" />
res/layout/digitalclock.xml
Xml代码 spinner" src="/Upload/Images/2015012114/4E072B8B8C20032D.gif" alt="" /><?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/time" android:textSize="45px" android:textStyle="bold" android:textColor="#FFFFFFFF" android:background="@drawable/bg" android:layout_width="wrap_content" android:layout_height="wrap_content" />
res/xml/est_appwidget.xml
Xml代码<?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="146dip" android:minHeight="72dip" android:updatePeriodMillis="1000" android:initialLayout="@layout/digitalclock" />
AndroidManifest.xml
Xml代码<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.studio.android.chp10.ex4" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name="ESTTime" android:label="@string/app_name"> <intent-filter> <action android:name= "android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/est_appwidget" /> </receiver> <service android:name=".ESTTime$UpdateService" /> </application> <uses-sdk android:minSdkVersion="3" /> </manifest>
Java代码
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.os.IBinder; import android.text.format.Time; import android.widget.RemoteViews; public class ESTTime extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) { context.startService(new Intent(context,UpdateService.class)); } public static class UpdateService extends Service { @Override public void onStart(Intent intent, int startId) { Time estTime = new Time("EST"); estTime.setToNow(); //传入所在包包名和布局文件 RemoteViews updateViews = new RemoteViews(getPackageName(),R.layout.digitalclock); updateViews.setTextViewText(R.id.time, estTime.format("%H:%M")); ComponentName thisWidget = new ComponentName(this, ESTTime.class); AppWidgetManager manager = AppWidgetManager.getInstance(this); manager.updateAppWidget(thisWidget, updateViews); } @Override public IBinder onBind(Intent intent) { return null; } } }
ESTTime.rar