java - 从 BroadcastReceiver 获取 Main Activity 数据
问题描述
我读了很多类似的问题,但我不知道该怎么做。我的 MainActivity 有这段代码:
MyBroadcastReceiver broad = new MyBroadcastReceiver();
broad.onReceive(context, new Intent("api6.intent.action.TRANSACTION_COMPLETED"));
然后在 MyBroadcastReceiver 中,除了主类之外,我有:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intents.ACTION_TRANSACTION_COMPLETED.equals(action)) {
if (intent.getExtras() != null) {
String txid = String.valueOf(intent.getExtras().get(Intents.INTENT_EXTRAS_TRANSACTION_ID));
}
}
}
}
在此行之后,我需要 MainActivity 中的 String txid:
broad.onReceive(context, new Intent("api6.intent.action.TRANSACTION_COMPLETED"));
解决方案
您可以通过多种方式实现,可以通过在 MainActivity 类中编写广播类或使用接口,在 MainActivity 中实现它
例如
MA extends AppCompat implements AnInterface{
onCreate(){
broadcast = new YourBroadcastClass(this);
}
@override
public void interfaceMethod(String value){
}
在你的广播类构造函数中
> AndInterface interface; MyBroad(AnInterface interface){ this.interface
> = interface; }
>
> and onReceive(){ interface.interfaceMethod("whatever you wanna send")
推荐阅读
- kotlin - 如何等待所有协程完成?
- r - 如何在 r 中为单独的函数生成给定数量的列?
- ios - 使用轻击手势识别器时未检测到几何元素,但它检测到 body-splitcontainers-split123
- java - Hibernate 命名查询
- python - 具有不规则时间序列的 groupby 后的 Pandas 数据帧过滤
- gitlab - 运行 gitlab-runner 几个步骤
- mysql - Mysql,Node,查询中的查询,如何从另一个查询中填充地图函数中的属性
- javascript - 无法在 Next.js 中获取动态组件以跳过服务器端渲染并仅在客户端上显示
- excel - 将新数据加载到工作表中时,我将使用什么公式使列自动填充到 Excel 中?
- python - 调用另一个函数时如何停止特定函数?