Kobeissi2 Kobeissi2 - 3 years ago 233
Android Question

Android: How can I send an SMS in the background? (API Min is 21)

I'm creating an Android application that sends out SMS messages. I've got everything working except for one issue; It does not send out messages unless the app is open.

My code for sending is basic:


SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, messageToSend, null, null);



I want the message to be sent on a specific time. I have the time stored in a String called timeToSend and it sends perfectly if the app is in the foreground. How can I get it to send the message in the background? I've read up on alarmmanagers but I'm not sure if that is what I need.

Thank you.

Answer Source

Like @CommonsWare said, you need to handle your specific time logic. Why not use an AlarmManager which will call a Service in which your code for sending the sms actually "happens". If you do use an AlarmManager, please note that different versions of Android will (likely) be handled by different methods related to AlarmManager, possibly including code to reset the AlarmManager (if necessary). You also have to be aware of changes to how Services are managed in "the background" from Marshmallow on....

**EDIT: ** Please be aware that when rebooting your device you will have to reset your AlarmManager as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download