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

本文详细阐述了如何在Android应用中通过AppWidgetProvider接收来自AppWidget的广播,并利用PendingIntent创建交互按钮,以及如何在接收到广播后更新AppWidget控件状态。重点介绍了在AppWidget和主程序不在同一进程时的更新机制,包括如何使用RemoteViews更新控件状态,并最终通过AppWidgetManager通知AppWidget进行更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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方法传入的参数不同(小细节)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值