Mars视频笔记——AppWidget(2)基础交互

本文详细介绍了如何在AppWidget中使用控件,特别是如何通过PendingIntent实现控件事件绑定,以及如何在不同进程间传递Intent,确保用户在点击AppWidget上的按钮时能够跳转至目标Activity。

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

 

AppWidget(2)控件监听器绑定

什么是PendingIntent

PendingIntent创建之后并不马上使用 PendingIntent将实际Intent包裹其中

AppWidget和应用程序运行在2个进程中

进程A将PendingIntent交给进程B 当B中发生某事件 则其中的Intent被执行

 

创建PendingIntent的方法 (PendingIntent类的静态方法)

1 getActivity(...)

2 getBroadcast(...)

3 getService(...)

RemoteViews的作用

RemoteViews对象表示了一系列的View对象(非应用程序同一进程的)

RemoteViews所表示的对象运行在另外的进程当中

AppWidget对于Activity就是一个RemoteViews

 

在AppWidget中使用控件

在ApppWidget中添加控件 例如一个Button 在layout中声明

为Button绑定处理器

AppWidget和应用程序不在同一进程中 要用:

remoteViews.setOnClickPendingIntent(R.id.widgetButtonId,pendingIntent);

 

主要在onUpdate方法中 其中有一个参数int[] appWidgetId 是桌面上创建的widget

 

	// 1 创建一个Intent
	Intent intent = new Intent(context,TargetActivity.class);
	// 2 创建一个PendingIntent
	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
	// 3 得到RemoteViews
	RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.example_appwidget);
	// 4 设置事件 绑定处理器 第一个参数是被绑定处理器控件的ID 第二个为动作
	remoteViews.setOnClickPendingIntent(R.id.widgetButtonId, pendingIntent);
	// 5 更新AppWidget 第一个参数指定更新哪一个 第二个参数为更新的控件
	appWidgetManager.updateAppWidget(appWidgetIds[i],remoteViews);
 

 

最终实现的是AppWidget上点击一个Button 跳转到TargetActivity

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值