简体   繁体   中英

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.

I think you could use AsyncTask , which runs in the background

The details on how to implement it are in this developer's page

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM