1. 定义一个WidgetProvider, 用来处理Widget的一些CallBack
OnEnable,创建第一个Widget时调用。
OnDisable, 和OnEnable相反,创建最后一个Widget调用。
OnDelete,Widget的一个实例被删除时调用。
OnUpdate,当Widget需要更新它的View时调用。
onReceive():此方法默认情况下处理BroadcastReceiver行为,并调用上面的方法。
public class WidgetDemoAppWidgetProvider extends AppWidgetProvider{
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length; // Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_demo_layout);
views.setOnClickPendingIntent(R.id.wap_app, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
2. 在AndroidManifast.xml 注册Provide
<receiver android:name="WidgetDemoAppWidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/widget_demo_appwidget_info" />
</receiver>
3. 创建Widget配置XML在xml文件夹下:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="60px"
android:minHeight="60px"
android:initialLayout="@layout/widget_demo_layout"
>
</appwidget-provider>
4. 创建Widget 的Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/wap_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
</LinearLayout>