W1ll
W1ll

Reputation: 177

How to pass data from a BroadcastReceiver from a second activity to a function in another activity

I need to send a data from a BroadcastReceiver from a second activity to a function in another activity but I do not know how to do it, someone could tell me how to do it.

This is the BroadcastReceiver of a second activity:

public class UsbService extends Service implements SerialPortCallback {    

private boolean statusUSB = false;

private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
            boolean ret = builder.openSerialPorts(context, BAUD_RATE,
                    UsbSerialInterface.DATA_BITS_8,
                    UsbSerialInterface.STOP_BITS_1,
                    UsbSerialInterface.PARITY_NONE,
                    UsbSerialInterface.FLOW_CONTROL_OFF);
            if(ret){
                Toast.makeText(context, "Usb Conectado!", Toast.LENGTH_SHORT).show();
                statusUSB = true;
            }else{
                statusUSB = false;
            }

        } else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {

            UsbDevice usbDevice = arg1.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            boolean ret = builder.disconnectDevice(usbDevice);
            Toast.makeText(context, "Usb Desonectado!", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(ACTION_USB_DISCONNECTED);
            arg0.sendBroadcast(intent);
        }
    }
};
.
.
.

The data I need to send is the Boolean statusUSB

This is a function of the first activity where I need to receive it to evaluate it:

public class MainActivity extends AppCompatActivity {
.
.
.
    public boolean checkUSB() {

    if (statusUSB == true){
        Toasty.success(this, "USB Conectado!",Toast.LENGTH_SHORT, true).show();
     }
    if (statusUSB == false){
        Toasty.error(this, "USB Desconectado!",Toast.LENGTH_SHORT, true).show();
    }

Upvotes: 0

Views: 40

Answers (1)

Larry Schiefer
Larry Schiefer

Reputation: 15775

What you describe is not something the Android dev model supports. Each Activity is independent with its own lifecycle (see here.) You do not directly call methods in an Activity from another Activity. If your 2nd Activity is being used to gather information which then needs to be reported to the 1st Activity, look into starting the 2nd Activity for result. Your 2nd Activity then just needs to set the result before it calls finish().

Upvotes: 1

Related Questions