Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from BroadcastReceiver class to a Android Activity [duplicate]

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

}

like image 631
ANJ Avatar asked Sep 09 '12 16:09

ANJ


People also ask

How pass data from BroadcastReceiver to activity in Android?

startActivity(i); Then, in your activity, you will need to getExtra as so: Intent intent = getIntent(); String message = intent. getStringExtra("message");

What is the role of the onReceive () method in the BroadcastReceiver?

Creating a BroadcastReceiver The onReceiver() method is first called on the registered Broadcast Receivers when any event occurs. The intent object is passed with all the additional data. A Context object is also available and is used to start an activity or service using context.

Is broadcast receiver deprecated?

What does saving battery have to do with BroadcastReceivers? With Android Nougat, the support for registering three different implicit BroadcastReceivers in your AndroidManifest was removed. With apps targeting Android O, all implicit BroadcastReceivers registered in the manifest (except these) will stop working.

What is the use of BroadcastReceiver in Android?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.


2 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.

like image 189
alyon2002 Avatar answered Oct 22 '22 06:10

alyon2002


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");
}
like image 2
Swayam Avatar answered Oct 22 '22 07:10

Swayam