`

Mars视频笔记——AppWidget(3)广播 控件更新

阅读更多

 

AppWidget3

接收来自AppWidget的广播

步骤:

1 在AndroidManifest.xml中为AppWidgetProvider注册新的intent-filter

<intent-filter>
	<action adroid="my.package.MYPACKAGE">
</intent-filter>

 

2 使用getBroadcast()方法创建一个PendingIntent

3 为AppWidget当中的控件注册处理器

在onUpdate方法中:

pulblic void onUpdate(Context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
	//创建一个Intent对象
	Intent intent=new Intent();
	//为Intent对象设置Action
	intent.setAction(MY_ACTION); //其中MY_ACTION为定义了的常量my.package.MYPACAGE
	//使用getBroadcast方法,得到PendingIntent对象,该对象执行时会发送一个广播(包含之前的intent)
	PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,intent,0);
	//之后按惯例得到RemoteViews,并绑定处理器
	RemoteViews remoteViews=new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
	remoteViews.setOnClickPendingIntent(R.id.widgetButtonId, pendingIntent);
	appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}

 

4 在onReceive方法中接收广播消息

当点击了widgeButton时 就会触发onReceive方法

从intent中得到action

if(MY_ACTION.equals(action)) 则匹配成功

更新AppWidget中控件的状态

要特别注意AppWidget和主程序不在同一个进程中,所以不能用普通方法

步骤:

1 在RemoteViews类中的一系列方法更新控件

例如各种set方法 setTextViewText setImageViewUri等

在onReceive方法中 匹配action后

 

//得到remoteViews
RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.example_appwidget);
//修改状态
remoteViews.setImageViewResource(R.id.imageId, R.drawable.aaa);
remoteViews.setTextViewText(R.id.widgetText,"test");

注意 别忘了调用super.onReceive(context,intent)方法 以便非自定义intent传入时候执行系统的onReceive

2 在使用RemoteViews更新控件状态之后 需要使用AppWidgetManager通知AppWidget进行该更新

 

//获得AppWidgetManager (这个对象在onUpdate中是作为参数传入的 但是onReceive中需要自己获取)
AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(context);
ComponentName componentName=new ComponentName(context,ExampleAppWidgetProvider.class);
appWidgetManager.updateAppWidget(componentName, remoteViews);

*RemoteViews代表widget中的控件 ComponentName代表整个widget

可以看到在onUpdate和onReceive中的updateAppWidget方法传入的参数不同(小细节)

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics