I am developing an application where i need to send an sms to a particular phone number. I can send the sms using following code.
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Now what i want is the sms should go automatically. The time, at which the message should go automatically, is stored in MySQL database.So i need the code that will keep on checking when that time comes and then send the message to that number automatically. Its a kind of reminder thing. The user will keep a reminder in application eg.; i need to get a message after 1 hour. So after 1 hour the message should come. PLz help??
Finally i got it.
/** Code For reminder is here */
int time=Integer.parseInt(answer);
int num = (int)System.currentTimeMillis();
Intent intent = new Intent(getApplication(), MyBroadcastReceiver.class);
intent.putExtra("phoneNo",phoneNo);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, time);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), num, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ calendar.getTimeInMillis() , pendingIntent);
Toast.makeText(getApplication(), "Alarm set in " + time + " minutes",
Toast.LENGTH_SHORT).show();
/** Code for reminder is over */
And my reciever code is
public void onReceive(Context context, Intent intent) {
String sms= "Your turn is about to come. Please be ready. Thank You";
String phoneNo;
Bundle extrasBundle = intent.getExtras();
phoneNo=extrasBundle.getString("phoneNo");
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(context, "SMS Sent to " + phoneNo,Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(context,"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Just in case someone might need this… Thanku
use AlarmManager for this purpose. Create a receiver, register it in manifest file.
with alarmaManager set an Alarm after particular time.
put your SendSMS code into Receiver’s on receive.
Edit : I answered this long back, it is not suitable for current scenarios, please read this blog for better alternatives Background schedulers instead.