2012-02-13 64 views
0

我想做一个短信安排应用程序,在预定义的时间发送短信。我决定为此使用计时器。在我的研究过程中,我发现Alarm Manager更适合在Android中安排一次事件。任何指导都是有益的。短信安排在Android中

我要实现我的服务计时器如图所示给予代码:

公共类SMSTimerService延伸服务{

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"); 

} 

}

+0

到目前为止你做了什么? – 2012-02-13 06:21:04

+0

@Seshu Vinay - 到目前为止,我已经拿起联系电话号码并保存了信息。我已经设置了短信应该发送的延迟时间。我的主要问题是我不知道如何执行调度。我很困惑定时器,报警管理器和计数器。 - – Prativa 2012-02-13 07:31:26

回答

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意味着一秒钟。

+0

我们是否可以在后台服务中实施计数器以发送短信 – Prativa 2012-02-13 06:02:50

+0

contd ...并且我们是否可以从BroadCast Receiver – Prativa 2012-02-13 06:03:49

+0

开始此服务,您可以使用首选项来保存已发送多少个短信,并在每次警报管理器开始 – ezcoding 2012-02-13 10:15:16