Search code examples
androidbroadcastreceiverandroid-pendingintentsmsmanager

How to abort BroadcastReceiver in android


I am making an SMS schedule app which will simply take time, sms and number from user and send this sms at a given time. I am using PendingIntent. Here is my sample code.

When user creates a schedule, it simply calls this method.

private void SendMessages()
    {
        Intent intent = new Intent(this, SMSBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, Timemilli, pendingIntent);
    }

And here is the 'SMSBroadcastReceiver.java' file

public class SMSBroadcastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "SMS Sent !!!!.", Toast.LENGTH_LONG)
                .show();
        // //Sms Sending

        try
        {
            SmsManager smsManager = SmsManager.getDefault();
            for (int i = 0; i < SMSScheduleContactsActivity.SelectedContacts.length; i++)
            {
                smsManager.sendTextMessage(
                        SMSScheduleContactsActivity.SelectedContacts[i], null,
                        AddNewSmsSchedule.Message, null, null);
            }

            Log.d("testllllllllllllllll", "Message Sent");
        }
        catch (Exception e)
        {   
            e.printStackTrace();
        }
    }

}

My question is: when user edits the schedule, how can I cancel that broadcast and send a new one??? As there can be more than one schedule, how to find the speicific to change/abort??


Solution

  • when user edits the schedule, how can I cancel that broadcast and send a new one?

    Call cancel() on AlarmManager with an equivalent PendingIntent to the one you used to set up the schedule:

    Intent intent = new Intent(this, SMSBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 234324243, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    
    alarmManager.cancel(pendingIntent);
    

    As there can be more than one schedule, how to find the speicific to change/abort?

    There is only one alarm in your implementation.