实现点击桌面上小插件的按钮后,发送一个广播消息,该消息会引发桌面小插件的一些改变
1.xml中的example_appwidget_info.xml没什么变化,layout中的example_appwidget.xml中一个文本框,一个图片,一个按钮。
2.manifest中注册
<receiver android:name="ExampleAppWidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter>
<action android:name="chris.appwidget3.UPDATE_APP_WIDGET" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/example_appwidget_info" />
</receiver>
3.ExampleAppWidgetProvider.java中首先定义一个常量字符串,该常量用于命名Action
private static final String UPDATE_ACTION="chris.appwidget3.UPDATE_APP_WIDGET";
复写那五个方法。
在onUpdate中,使用一个remoteViews,代表运行在其他进程当中的一系列对象,然后利用remoteViews来给桌面上的Appwidget的按钮绑定监听器,点击后,会触发pendingIntent,pendingIntent发送一个广播,广播内容是一个intent,intent的动作是UPDATE_ACTION。发出这个广播后,就依靠onReceive来接收广播,然后做相应操作。
//创建一个Intent对象
Intent intent = new Intent();
//为Intent对象设置Action
intent.setAction(UPDATE_ACTION);
//使用getBroadcast方法,得到一个PendingIntent对象,当该对象执行时,会发送一个广播
//PendingIntent,像一个锦囊,它由进程A创建,但是由进程B使用,并且不是立刻使用,而是在一定的触发条件下使用。就像appwidget运行在桌面进程中,而程序运行在自己的进程中
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//remote是远程的意思,remoteViews对象代表一系列的view对象。它所表示的对象运行在另外的进程当中。这里代表当前包的R.layout.example_appwidget中的文本,图片,按钮,三个view。
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
//为appwidget的按钮,绑定监听器,点击后,会调用pendingIntent。
remoteViews.setOnClickPendingIntent(R.id.widgetButtonId, pendingIntent);
//更新appWidget
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
在onReceive中,
//获取action
String action = intent.getAction();
//对比action是否是UPDATE_ACTION
if (UPDATE_ACTION.equals(action)) {
//使用remoteViews来获取运行在其他进程当中的一系列对象,这里是指那一个文本,一个图片,一个按钮
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.example_appwidget);
//改变图片和文本
remoteViews.setImageViewResource(R.id.imageId, R.drawable.second);
remoteViews.setTextViewText(R.id.widgetTextId, "可能唱的最差可是我是籁赋,live决定我的气场气势气度");
//更新appWidget,因为onReceive的传入参数中没有AppWidgetManager,所以要先获取他。
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, ExampleAppWidgetProvider.class);
appWidgetManager.updateAppWidget(componentName, remoteViews);
}else{
//因为在manifest中,action并非只有用户自定义的UPDATE_ACTION,还有系统的APPWIDGET_UPDATE,所以也要进行处理
super.onReceive(context, intent);
这次遇到的问题是,要在example_appwidget_info.xml设置合适的高度宽度,不然,就会悲剧的放不下那三个view
点击按钮前:

点击按钮后:

代码