8

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

}

ANJ
  • 301
  • 1
  • 2
  • 14
  • maybe this is what you need [Listener Implementation for a BroadCaster][1] [1]: http://stackoverflow.com/questions/6661801/how-can-i-send-result-data-from-broadcast-receiver-to-activity –  Jun 17 '14 at 15:56

4 Answers4

14

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.

Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
alyon2002
  • 265
  • 4
  • 7
2

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");
}
Swayam
  • 16,294
  • 14
  • 64
  • 102
  • 1
    It throws an exception and it is not good practice to start an activity from broadcast receiver. You can avoid exception by adding flag `FLAG_ACTIVITY_NEW_TASK` to intent. – Wojtek Jan 16 '18 at 08:08
  • Thank you for pointing this out. Have added it to the answer. – Swayam Feb 01 '18 at 08:58
  • @Swayam How to pass data if i used pending intent – Gowthaman M Feb 01 '18 at 09:01
  • @GowthamanM Can you please share a link to your question along with the code snippet? I will be able to answer it exactly then. :) – Swayam Feb 01 '18 at 13:01
  • @Swayam https://stackoverflow.com/questions/48559566/how-to-pass-data-to-broadcastreceiver-to-activity-using-pendingintent?noredirect=1#comment84115752_48559566 Thank you sir..i solved my pbm...can you please check what i did is correct or not..it's working fine for i donot it's proper way doing or not – Gowthaman M Feb 01 '18 at 13:09
0

WE can send the data from onReceive to another activity using LocalBroadcastManager. It means you are again broadcasting the data using the context

@Override public void onReceive(Context context, Intent intent) {

Log.d("Broadcast", "wifi  ConnectivityReceiver");

        Bundle extras = intent.getExtras();
        Intent intent = new Intent("broadCastName");
        // Data you need to pass to another activity
        intent .putExtra("message", extras.getString(Config.MESSAGE_KEY)); 
        context.sendBroadcast(intent );

}

-1

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);
    }
}
Robert
  • 5,278
  • 43
  • 65
  • 115