【问题标题】:Get in the Main Activity data from a BroadcastReceiver从 BroadcastReceiver 获取 Main Activity 数据
【发布时间】:2019-06-06 15:22:03
【问题描述】:

我阅读了很多类似的问题,但我不知道该怎么做。我的 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 中的字符串 txid 就在这一行之后:

         broad.onReceive(context, new Intent("api6.intent.action.TRANSACTION_COMPLETED"));

【问题讨论】:

  • 查看下面的非正式答案,

标签: java android broadcast


【解决方案1】:

你可以通过很多方式实现,要么在 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")

【讨论】:

  • 谢谢,我试了很多次,还是不行。我收到此错误:MyBroadcastReceiver> 没有零参数构造函数
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多