Search code examples
androidnotificationsalarmmanagersmsmanager

How to Send sms periodically after a fixed time automatically


I need to send an SMS to a number periodically in background after a fixed time. How can tat be done. Thanks.


Solution

  • Here is the code to repeatedly send sms with a initial delay and delay between each message.

    static private Handler handler = new Handler();
    Runnable task = new Runnable() {
        public void run() {
            sendSMS("123456", "Test Message");
            if (!stopped) {
                handler.postDelayed(this, interval);
            }
        }
    };
    
    public void start() {
        handler.postDelayed(task, initialDelay);
    }
    
    private void sendSMS(String phoneNumber, String message)
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }