1 、创建一个AppWidgetProvider
public class ExampleAppWidgetProvider extends AppWidgetProvider { //定义一个常量字符串,该常量用于命名Action private static final String UPDATE_ACTION = "mars.appwidget03.UPDATE_APP_WIDGET"; //定义一个常量字符串,用于杀死app private static final String KILL_APP = "com.rui.app.KILL_APP"; @Override public void onDeleted(Context context, int[] appWidgetIds) { // TODO Auto-generated method stub super.onDeleted(context, appWidgetIds); } @Override public void onDisabled(Context context) { // TODO Auto-generated method stub super.onDisabled(context); } @Override public void onEnabled(Context context) { // TODO Auto-generated method stub super.onEnabled(context); } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); String action = intent.getAction(); Log.i("TAG", action); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.i("TAG", "==================================="); //创建一个Intent对象 Intent intent = new Intent(); //为Intent对象设置Action intent.setAction(KILL_APP); //使用getBroadcast方法,得到一个PendingIntent对象,当该对象执行时,会发送一个广播 PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.example_appwidget); remoteViews.setOnClickPendingIntent(R.id.widgetButtonId, pendingIntent); appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); }
2 、在layout下面创建一个用于显示内容的布局 example_appwidget.xml
<?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" > <Button android:id="@+id/widgetButtonId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="测试用按钮" /> </LinearLayout>
3 、再在res下面的xml下面新建一个 xml (example_appwidget_info.xml)文件来指定此widget的一些信息:
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="294dp" android:minHeight="72dp" android:updatePeriodMillis="5000" android:initialLayout="@layout/example_appwidget" > </appwidget-provider>
4 、 最后在 AndroidManifest.xml 中配置此widget的一些必须信息:
<receiver android:name="ExampleAppWidgetProvider">
<intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <intent-filter> <action android:name="mars.appwidget03.UPDATE_APP_WIDGET"/> </intent-filter> <intent-filter> <action android:name="com.rui.app.KILL_APP"/> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/example_appwidget_info" /> </receiver>