Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from BroadcastReceiver

I'm trying to make the app detect when a new SMS is received.
For doing this I registered programatically a new BroadcastReceiver, where I process the incoming SMSs and then it should return a value, that the fragment that registered the BroadcastReceiver should retrieve.
I can't get to retrieve the value returned from the BroadcastReceiver. I've seen other StackOverflow questions about returning values to Activities, but they always end up creating a new Activity. I don't want that. I want to get the value in the same place where I registered the BroadcastReceiver. How should I do this?

This is the code from the BroadcastReceiver:

public class RegisterSms extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {

        // stuff...
        this.setResultData("data to return");

    }
}

In the fragment I'm doing this:

BroadcastReceiver smsReceiver = new RegisterSms();
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
this.getContext().registerReceiver(smsReceiver, filter);
// here I should be receiving the data sent by the BroadcastReceiver
like image 261
Berna Avatar asked Mar 02 '26 09:03

Berna


1 Answers

Create your broadcast receiver as an anonymous inner class.

private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //here you can parse intent and get sms fields.
        }
    };
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
this.getContext().registerReceiver(smsReceiver, filter);
like image 132
Dominik Suszczewicz Avatar answered Mar 04 '26 23:03

Dominik Suszczewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!