1、在res/xml下创建配置文件appwidget_provider.xml。
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="60dp"
android:minHeight="30dp"
android:updatePeriodMillis="86400000"
android:initialLayout="@layout/appwidget_provider"
android:configure="com.example.appwidgetsample.ExampleAppWidgetConfigure"
android:resizeMode="horizontal"
>
</appwidget-provider>
2、通过扩展系统类AppWidgetProvider来实现,主要是重写里面的函数来完成你所需要的功能。
1) public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
}
向桌面添加一个小部件时调用。
2) public void onDeleted(Context context, int[] appWidgetIds) {
}
窗口小部件被删除时调用。
public class ExampleAppWidgetProvider extends AppWidgetProvider {
// log tag
private static final String TAG = "ExampleAppWidgetProvider";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
// For each widget that needs an update, get the text that we should display:
// - Create a RemoteViews object for it
// - Set the text in the RemoteViews object
// - Tell the AppWidgetManager to show that views object for the widget.
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
String titlePrefix = ExampleAppWidgetConfigure.loadTitlePref(context, appWidgetId);
updateAppWidget(context, appWidgetManager, appWidgetId, titlePrefix);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
// When the user deletes the widget, delete the preference associated with it.
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
ExampleAppWidgetConfigure.deleteTitlePref(context, appWidgetIds[i]);
}
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
// When the first widget is created, register for the TIMEZONE_CHANGED and TIME_CHANGED
// broadcasts. We don't want to be listening for these if nobody has our widget active.
// This setting is sticky across reboots, but that doesn't matter, because this will