问题
I want to make an SMS scheduling app, that sends SMS at predefined time. I have decided to use a timer for that purpose. During my research, I found out that Alarm Manager was more appropriate option for scheduling one time events in android. Any guidance would be fruitful.
I want to implement the timer in my service as shown in the give code:
public class SMSTimerService extends Service {
private Timer timer = new Timer();
Long delay = 10000L;//for long we have to keep L at the last of the integer;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;//null means we are not using any IPC here
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("prativa","service has started");
startService();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("prativa","service is destroying");
shutdownService();
}
/*
* starting the service
* */
private void startService()
{
TimerTask task = new TimerTask(){
@Override
public void run() {
sendSMS();
}};
timer.schedule(task, delay);
}
private void sendSMS()
{
String phone = "5556";
String message = "This is my test message";
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phone, null, message, null, null);
}
private void shutdownService()
{
if(timer != null)
timer.cancel();
Log.i("Prativa","Timer has stopped");
}
}
回答1:
this is what I have for you:
http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/
Edit: How to trigger a broadcast via the AlarmManager:
Intent broadCastIntent = new Intent(this, "YOURBROADCASTRECEIVER.class");
PendingIntent intent = PendingIntent pendingIntent = PendingIntent.getBroadcast(
this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
AlarmManager.INTERVAL_HOUR, pendingIntent);
Note that this alarm will set off immediately the first time. If you want to set it of later you can multiply "System.currentTimeMillis() * x" where x = 1000 would mean one second.
来源:https://stackoverflow.com/questions/9256088/sms-scheduling-in-android