Home » Android » Pass data from BroadcastReceiver class to a Android Activity

Pass data from BroadcastReceiver class to a Android Activity

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m developing an Android application and it has a functionality that while the application is running if I receive an new SMS message the content of that message need to be read using TextToSpeech. I know how to read a text using TextToSpeech. I have written two classes on my application. one is MainActivity extends from Activity and the other one is SmsReceiver extends from BroadcastReceiver. When a Sms is received while the MainActivity is running I want get the content of the sms message using SmsReceiver and pass it to MainActivity and then read it inside MainActivity using TextToSpeech. How can I pass the content of the sms from SmsReceiver to my MainActivity. A copy of my SmsReceiver class is pasted bellow.

public class SmsReceiver extends BroadcastReceiver{


@Override
public void onReceive(Context context, Intent intent) {
    //this stops notifications to others
    this.abortBroadcast();

    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();   
    SmsMessage[] msgs = null;
    String from = null;
    String msg= null;
    String str = "";            
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];            
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
            str += "SMS from " + msgs[i].getOriginatingAddress();
            from = msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            msg = msgs[i].getMessageBody().toString();
            str += "\n"; 
        }
        System.out.println("from "+from);
        System.out.println("msg "+msg);
        Toast.makeText(context, "SMS Received : ",Toast.LENGTH_LONG).show();

        //continue the normal process of sms and will get alert and reaches inbox
            this.clearAbortBroadcast();
        }
}

}

How to&Answers:

Using an interface is a solution that worked for me.

In your BroadcastReceiver put the following

public interface OnSmsReceivedListener {
    public void onSmsReceived(String sender, String message);
}

then add the listener

private OnSmsReceivedListener listener = null;

then add a method to the BroadcastReceiver..

public void setOnSmsReceivedListener(Context context) {
    this.listener = (OnSmsReceivedListener) context;
}

then in your onReceive method you can do something like this…

if (listener != null) {
    listener.onSmsReceived(sender, msg);
}

in the activity that creates and registers the BroadcastReceiver start by implementing the OnSmsReceivedListener interface, then do the following

public class SomeActivity extends Activity implements OnSmsReceivedListener.....

private MissedCallActivity receiver;

in the onCreate method add

receiver = new MissedCallActivity();
receiver.setOnSmsListener(this);

then override the method used by the interface.

@Override
public void onSmsReceived(String sender, String message) {
    //Insert your text to speech code here
}

That should do the trick.

Also, don’t forget to register your receiver in the onResume() method and unregister it in the onPause() method. Also, see how “from” is highlighted in blue? That means it’s part of the Java syntax and cannot be used as a variable.

Answer:

You can pass data using intents.

In your BroadcastReceiver, create an Intent:

Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("msgContent", msg);
i.putExtra("sender",from);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // adding this flag starts the new Activity in a new Task 
startActivity(i);

Then in the other Activity, you can get those values like :

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String messageContent = extras.getString("msgContent");
    String messageSender = extras.getString("sender");
}

Answer:

Use the CONTEXT and INTENT arguments in onReceive()

public class MissedCallActivity extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
            intent.putExtra("Number", Var_Number);
            intent.setClass(context, ReadContactsActivity.class);
            context.startActivity(intent);
    }
}