Berna
Berna

Reputation: 131

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

Upvotes: 3

Views: 4964

Answers (1)

Dominik Suszczewicz
Dominik Suszczewicz

Reputation: 1499

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);

Upvotes: 4

Related Questions