Search code examples
androidbroadcastreceiver

PendingIntent not working after colsing activity


I am developing an application to send SMS in android.

I also need to find if message is delivered or not. I have tried to register a receiver to find Delivering SMS , It's working very well if I don't stop activity until sms is delivered. But if I close activity before delivering message , delivery receiver will not work.

what should I do?

here is what i have done(Inside a function in my Activity):

try
{
SmsManager smsManager = SmsManager.getDefault();

String to = "5556";
String body = "Test Message";

String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";


PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,new Intent(DELIVERED), 0);

registerReceiver(new BroadcastReceiver()
{
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        switch (getResultCode())
        {
            case Activity.RESULT_OK:
                Toast.makeText(arg0, "SMS sent", Toast.LENGTH_LONG).show();
                break;
                default:
                Toast.makeText(arg0, "Error", Toast.LENGTH_LONG).show();
                break;
        }
    }
}, new IntentFilter(SENT));


registerReceiver(new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent arg1) 
    {
        switch (getResultCode())
        {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_LONG).show();

                break;
            default:
                Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_LONG).show();
                break;                        
        }
    }
}, new IntentFilter(DELIVERED));        

smsManager.sendTextMessage(to.getText().toString(), null, body.getText().toString(), sentPI, deliveredPI);
}
catch(Exception ex)
{
    Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}

Solution

  • Your BroadcastReceiver is registered dynamically in your Activity, and is therefore tied to the Activity's lifecycle. To receive broadcasts even when your Activity is not running, you need to statically register your BroadcastReceiver class in your manifest.

    Note that you can use the same BroadcastReceiver class for both your Sent and Delivered broadcasts.