1、配置一个appwidget-provider,放在res/xml/weather_info.xml
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth = "125px"
android:minHeight = "105px"
android:updatePeriodMillis = "3600000"//这个是自动更新的时间,不过都失效了,至于原因嘛
android:initialLayout = "@layout/main">
</appwidget-provider>
2、配置你的manifest.xml
<receiver android:name=".weather"
android:label="@string/app_name"
android:icon="@drawable/icon"
>
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/weather_info" />
</receiver>
3.实现一个AppWidgetProvider类,覆盖相关的方法
相关方法的何时会回调看看文档或者其他的人博文吧!
4、配置一个远程的视图,然后配置该远程视图
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
PendingIntent Pintent= PendingIntent.getActivity(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget, Pintent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
下面我会上传一个例子,我认为最有特点的部分就是定义了一个server实现自动更新!
public static final class UpdateService extends Service {
private RemoteViews updateViews;
private ComponentName thisWidget;
private AppWidgetManager manager;
@Override
public void onCreate()
{
super.onCreate();
updateViews = new RemoteViews(getPackageName(), R.layout.digitalclock);
thisWidget = new ComponentName(this, ESTTime.class);
manager = AppWidgetManager.getInstance(this);
}
@Override
public void onStart(Intent intent, int startId) {
/*用一个新的线程来实现定时更新*/
new Thread(){
@Override
public void run()
{
while(true){
Time estTime = new Time();
estTime.setToNow();
updateViews.setTextViewText(R.id.time,estTime.format("%H:%M"));
manager.updateAppWidget(thisWidget, updateViews);
/*定时*/
try{sleep(1000);} catch (InterruptedException e){}
}
}
}.start();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}