Android平台下Widget的搭建過程為:
1.在res/layout下建立Widget的布局檔案:digitalclock.xml
代碼
<?xml version="1.0" encoding="UTF-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/time"
android:textSize="45px"
android:scrollX="30px"
android:scrollY="30px"
android:textStyle="bold"
android:textColor="#ff000000"
android:background="@drawable/bg"
/>
2.在res/xml下建立Widget的描述檔案:est_appwidget.xml
代碼
<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="186dip"
android:minHeight="212dip"
android:updatePeriodMillis="1000"
android:initialLayout="@layout/digitalclock"/>
3. 從AppWidgetProvider繼承一個類(ESTTime),重寫其虛方法
代碼
package com.android.test.esttime;
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 {
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context,
AppWidgetManager appWidgetManager,int[] appWidgetIds )
{
context.startService(new Intent(context,UpdateService.class));
}
//Service類
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) {
// TODO Auto-generated method stub
return null;
}
}
}
4.在AndroidManifest.xml中註冊本Widget
代碼
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.test.esttime"
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>
最後,編譯運行。這樣在Home上長按彈出的Widget列表中就有新建立的Weiget了 。