在android中的短信调度

时间:2012-02-13 05:43:14

标签: android sms scheduling

我想制作一个短信调度应用,在预定义的时间发送短信。我决定为此目的使用计时器。在我的研究过程中,我发现Alarm Manager更适合在android中安排一次事件。任何指导都会富有成效。

我想在我的服务中实现计时器,如给定代码所示:

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 个答案:

答案 0 :(得分:3)

这就是我给你的东西:

  

http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/

编辑:如何通过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);

请注意,此闹钟将在第一时间立即启动。如果你想稍后设置它,你可以乘以“System.currentTimeMillis()* x”,其中x = 1000意味着一秒。

相关问题