2013-10-27 40 views
0

我需要幫助,以便在鬧鈴管理器指定的時間到期後自動停止某項服務。下面是代碼:在鬧鈴時間後使用鬧鈴管理器呼叫停止服務

Intent c = new Intent(getApplicationContext(), CallService.class);       
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, c, 0);   
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
alarm.set(AlarmManager.RTC_WAKEUP, 9*10000, pintent); 

即使在指定到期服務的時間保持在後臺運行,我怎麼能停止該服務立即停止時間到期後?

+0

我有一個使用Timertask的初始想法,當服務開始倒計時,並在確切的時刻停止服務。這是一種正確的方法還是非常耗費資源? – Psypher

回答

0

我用的TimerTask取消指定的時間後意圖:

Timer t = new Timer(); 
    TimerTask welcome = new TimerTask(){ 

     @Override 
     public void run() { 
     //Stopped the service 
     } 
    }; 
    t.schedule(welcome, 300, 30000); 

下面的網頁有關於如何使用TimerTask的 http://www.codeproject.com/Questions/413950/TimerTask-in-Android

+0

劑量它可以與你一起工作 –

+0

雅它爲我工作.. – Psypher

0

呼叫alarm.cancel(pintent)的詳細信息; 在指定的時間睡眠後嘗試此操作,或者將其寫入alarm.set(); 很可能它只會在時間到期後纔會被調用。如果這樣做並不符合指定時間使用thread.sleep的目的,然後調用 alarm.cancel(pintent);