2013-10-11 89 views
-1

這是我正在努力完成並嚴重失敗。服務和報警管理器

我需要:

-start服務

待辦事宜一些任務

-set AlarmManager的時間

設定時間 - 停止服務後重新啓動該服務

我遇到的問題是服務幾乎立即停止重新啓動。我要的是,警報響起後,服務應該啓動..

下面是代碼: -

Intent intent = new Intent(ThisService.this, 
          ThisService.class); 
    PendingIntent pendingIntent = PendingIntent.getService(ThisService.this, 0, 
            intent, PendingIntent.FLAG_CANCEL_CURRENT); 
    alarmManager.cancel(pendingIntent); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
          getUpdateTime(), getUpdateTime(), pendingIntent); 
    stopSelf(); 
+0

代碼在哪裏?在爲第一個服務使用完成一些任務後,在此處添加 –

+0

** stopService()**將意向傳遞給您的服務類,然後在服務停止後,您可以創建一個警報管理器實例並在一段時間後再次啓動服務 檢查這也是http://developer.android.com/reference/android/content/Context.html#stopService(android.content.Intent) –

+0

我只是想停止當前的服務,並讓AlarmManager之後再次創建相同的服務時間 – d3m0li5h3r

回答

1

你缺少的是廣播reciever

的流量應

  1. 啓動服務。
  2. 在服務執行任務
  3. 設置報警,觸發廣播Recievr(上bradcast reciever開始服務的接收一次。)創建廣播Reciever
  4. 呼叫StopSelf它就會停止你的服務,它可以從廣播重新啓動recievr

請參考http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html


//-----Set the alarm to trigger the broadcast reciver----------------------------- 
Intent intent = new Intent(this, MyBroadcastReceiver.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(
     this.getApplicationContext(), 234324243, intent, 0); 
     AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
     alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() 
     + (i * 1000), pendingIntent); 
     Toast.makeText(this, "Alarm set in " + i + " seconds", 
     Toast.LENGTH_LONG).show(); 

//---------------Call StopSelf here-------------------- 

//---------------------------------------------------------------------------------- 




public class MyBroadcastReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

//-----------write code to start the service-------------------------- 
    } 

    } 
+0

嘗試過..仍然沒有成功..它仍然沒有被推遲..服務正在被立即回叫。我猜測'setRepeating()'方法的參數可能不正確... – d3m0li5h3r

+0

如果您只是設置鬧鐘一次使用設置,而不是設置重複 –

+0

甚至嘗試與'set()'仍然是相同的概率 – d3m0li5h3r