faizal faizal -4 years ago 447
Android Question

call activity method from broadcast receiver

In the main activity, a layout is loaded that has some input fields and a submit button. When the submit button is clicked, the onClick handler method sends an sms back to the same mobile number :

SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, "hi", null, null);

There is a broadcast receiver defined that intercepts the message :

public class SmsReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
Bundle pdusBundle = intent.getExtras();
Object[] pdus=(Object[])pdusBundle.get("pdus");
SmsMessage messages=SmsMessage.createFromPdu((byte[]) pdus[0]);


Now, from the broadcast receiver, I want to call a function(with parameter), which is within my main activity. Is that possible? If yes, what kind of code should i add in my broadcast receiver ?

Answer Source

Thanks @Manishika. To elaborate, making the Broadcastreceiver dynamic, instead of defining it in the manifest, did the trick. So in my broadcast receiver class, i add the code :

MainActivity main = null;
void setMainActivityHandler(MainActivity main){

In the end of the onReceive function of the BroadcastReceiver class, I call the main activity's function :


In the main activity, I dynamically define and register the broadcast receiver before sending the sms :

SmsReceiver BR_smsreceiver = null;
            BR_smsreceiver = new SmsReceiver();
            IntentFilter fltr_smsreceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download