首页 > 解决方案 > 从 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"));

标签: javaandroidbroadcast

解决方案


您可以通过多种方式实现,可以通过在 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")

推荐阅读