androidsmsalarmmanager

How to schedule text messages to be sent at a later time in android?


I'm trying to schedule text messages in my Android application. The text message is being sent, except it won't get 'scheduled'. Here is my code for the same.

Intent myIntent = new Intent(ScheduleMessage.this, MyAlarmService.class);

Bundle bundle = new Bundle();
bundle.putCharSequence("Number", Number.getText().toString());
bundle.putCharSequence("Message", Message.getText().toString());
myIntent.putExtras(bundle);

pendingIntent = PendingIntent.getService(ScheduleMessage.this, 0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.SECOND,20);

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Toast.makeText(getApplicationContext(), "Message: "+Message+" for Number: "+Number, 1).show();

Am I missing something obvious? There's no force close or any error. Just that, the text message is sent IMMEDIATELY and not after 30 seconds(I'll later consider scheduling by the hour, day, etc). Please help me. I'm quite new to Android.


Solution

  • It depends on the exact current time when executing the code. :)

    What you do is take the CURRENT time (e.g. 09:19:35), then set the seconds part to 20 (e.g. 09:19:20). For 40 seconds each minute, that's a time in the past, triggering your alarm immediately.

    What you meant to write is:

    calendar.add(Calendar.SECOND,20);
    

    Notice the add method, where you wrote set.