从BroadcastReceiver获取主要活动数据

时间:2019-06-06 15:22:03

标签: java android broadcast

我读了很多类似的问题,但是我不知道该怎么做。我的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"));

1 个答案:

答案 0 :(得分:0)

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