最后您还需要创建在清单中声明的ExampleAppWidgetProvider类。例如,如果您想要一个用于单击的按钮小组件,使用AppWidgetProvider实现的示例代码如下。
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class ExampleAppWidgetProvider 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
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
// Intent intent = new Intent(context, ExampleActivity.class);
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button,其中appwidget_provider_layout为创建的xml布局文件名称
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
代码配置说明如下。
此AppWidgetProvider仅定义onUpdate()方法,并定义启动活动的PendingIntent,使用setOnClickPendingIntent(int,PendingIntent)将其添加到小组件的按钮上。
关于AppWidgetProvider的使用说明如下。
AppWidgetProvider回调通过onUpdate()方法。如果您的小组件需要接受用户的交互事件(此时您需要在此回调中注册事件处理程序),并且您的小组件不需要创建临时文件或数据库,也不需要执行其他清理的工作时,您无需关心除onUpdate()以外的生命周期回调。
说明 由于AppWidgetProvider是BroadcastReceiver的子类,因此不能保证您的进程在回调方法返回后仍能继续运行(有关广播生命周期的信息,请参见onUpdate()方法,通过在方法中启动服务来处理耗时操作。您可以从服务内部对小组件执行自己的更新,从而不必担心AppWidgetProvider会由于Application Not
Responding(ANR)而关闭。