2012-02-13 62 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