android - 将数据传递给 Intent / BroadcastReceiver
问题描述
我正在调用一个意图,并且该程序包是我无法控制的另一个应用程序。我已经设置了一个 BroadcastReceiver 来监听并从意图中获取一段数据。这在我附加的代码中完美运行。
我的问题是我现在需要根据我想从调用意图的活动传入的数据执行不同的操作。
有没有办法将数据从我的活动传递到我可以使用的广播接收器?任何和所有的帮助表示赞赏。
我尝试使用捆绑包(putString 和 getString),但是当意图启动时,它是第 3 方意图,唯一的捆绑包是他们提供给我的数据。我试图传递的捆绑包不存在。
从 MainActivity 调用
getTickets.setOnClickListener {
Log.i("Track", "MA1: " + Date().toString())
if (checkOrientation()) {
intent = Intent()
intent.setAction("com.trakitgps.GET_VEHICLE_NUM")
intent.setPackage("com.trakitgps")
val filter = IntentFilter("com.trakitgps.GET_VEHICLE_NUM_RESPONSE")
registerReceiver(receiver, filter)
startActivity(intent)
}
}
广播接收器
class TrackItReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
"com.trakitgps.GET_VEHICLE_NUM_RESPONSE" -> {
val truckNbr = intent.extras.getString("vehicleNum")
val errorMsg = intent.extras.getString("errorMsg")
val newIntent = Intent(context, TruckTicketsActivity::class.java)
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
newIntent.putExtra("assignedTruck", truckNbr)
newIntent.putExtra("truckError", errorMsg)
context.startActivity(newIntent)
}
}
}
}
解决方案
当然。
创建 时BroadcastReceiver
,将构造函数中需要的数据传递给它。然后,当onReceive()
被调用时,它就有了它需要的数据。像这样的东西:
// Create the BroadcastReceiver
BroadcastReceiver receiver = new MyReceiver(data, another, andAnother);
registerReceiver(receiver, filter)
startActivity(intent)
在MyReceiver
中,将成员变量声明为持有data
,another
并andAnother
在构造函数中对其进行初始化。
推荐阅读
- java - 单击复选框时显示 Edittext 和 Textview
- infiniband - 启用 RDMA 的 NIC 会进行字节序转换吗?
- compiler-construction - 如何在 JavaCC 中为整数编写正则表达式?
- jquery - 直接链接到选项卡式内容 - jquery 选项卡
- android - AAPT:错误:找不到资源,但它存在于 styles.xml
- r - 从 data.frame 创建矩阵并计算常见值
- api - Google OAuth & API:空白登录,因为 localhost 未“列入白名单”
- kubernetes - Kubernetes 1.11 找不到指标的 heapster
- powerbi - 替换 Power BI 中的特殊字符
- python - Python fork 和内存管理问题