2011-10-31 44 views
1

我有一個更新服務,啓動時啓動。事情是我希望它做一個檢查,然後等待一段時間,然後重新啓動。當我的服務綁定到應用程序時,我用鬧鐘做了這個,但現在它是獨立的,我只使用廣播接收器在啓動時啓動它。問題是,現在由於某種原因,我無法將鬧鐘與它集成在一起。 我只有我的UpdateService類和我的broadcastreceiver class.My代碼迄今在broadcastreceiver是這樣,但我想在這裏把鬧鐘說安排服務每30秒啓動一次。我真的需要這個。用定時器/鬧鐘啓動時更新服務

@Override 
public void onReceive(Context context, Intent intent) { 

    Intent startServiceIntent = new Intent(context, UpdateService.class); 
    context.startService(startServiceIntent); 
} 

歡迎任何建議。提前致謝。

回答

1

我找到了答案,我的問題:

private boolean service_started=false; 
private PendingIntent mAlarmSender; 

@Override 
public void onReceive(Context context, Intent intent) { 
    if(!service_started){ 
     // Create an IntentSender that will launch our service, to be scheduled 
     // with the alarm manager.  
     mAlarmSender = PendingIntent.getService(context, 
       0, new Intent(context, UpdateService.class), 0); 

     //We want the alarm to go off 30 secs from now. 
     long firstTime = SystemClock.elapsedRealtime(); 
     // Schedule the alarm!  
     AlarmManager am = (AlarmManager)context.getSystemService(context.ALARM_SERVICE); 
     am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
       firstTime,30*1000, mAlarmSender);  

     service_started=true; 
    } 
} 

最後,我的問題是,我沒有得到正確的背景如下:

(AlarmManager)getSystemService(ALARM_SERVICE); 

改爲 (AlarmManager)上下文.getSystemService(context.ALARM_SERVICE);