关于Intent内容传递action, category, data(Uri), type

本文深入探讨了Android中PendingIntent的使用方法,特别是如何通过Intent携带数据实现组件间通信。作者在实践中遇到buttonId始终为0的问题,并详细分析了解决方案,强调了在创建PendingIntent时正确设置Intent的必要性。

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

新人,对intent的使用也只是用在比较浅层,一直将其定义为组件之间数据传递的桥梁。

但是:

昨天在编写一个widget DEMO的过程中,连续通过

getPendingIntent
调用已经封装好的pendingIntent

remoteViews.setOnClickPendingIntent(R.id.btn0, getPendingIntent(context, 0))
remoteViews.setOnClickPendingIntent(R.id.btn1, getPendingIntent(context, 1));
remoteViews.setOnClickPendingIntent(R.id.btn2, getPendingIntent(context, 2));
remoteViews.setOnClickPendingIntent(R.id.btn3, getPendingIntent(context, 3));
PendingIntent封装intent,

	private PendingIntent getPendingIntent(Context context, int buttonId) {
		Intent intent = new Intent("com.jes.action.STATE_CHANGE");
		intent.setClass(context, TestWidgetProvider.class);
		intent.putExtra("BUTTON_ID", buttonId);
		Log.i("pendingIntent","buttonId : "+ buttonId);
		// intent.setData(Uri.parse("custom:" + buttonId));
		pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
		return pendingIntent;
	}

广播接收器如下:

 if (action.equals("com.jes.action.STATE_CHANGE")) {
	Log.i("onReceive", "action:" + action);
	int buttonId = intent.getIntExtra("BUTTON_ID", -1);
	Log.i("receiver", "button :" + buttonId);
}

结果发现接受到的buttonId值却始终为0,即第一个getPendingIntent的参数内容


后来发现,似乎是因为PendingIntent.getBroadcast() 所得到的pendingIntent对象在生成的时候,因为只是传递数据内容存在差异,所以得到的也就只有一个对象,想要区分不同 pendingIntent,需要在前提Intent中添加能够区分的相关数据,具体如下几个:

主要比较了Intent的action, category, data(Uri), type,


具体解释可以Google下ANDROID INTENT,已经有了很多对INTENT的使用机制等




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值