2011-09-22 100 views
1

在我的應用程序中,我想在特定的時間段內使用報警服務。我從用戶處獲取開始時間和結束時間值並將其保存在數據庫中,現在我想在開始時間和警報應該在用戶指定的結束時間結束。我對這個主題不熟悉,並且不能理解如何實現這個...任何幫助將不勝感激。謝謝你。在android中啓動報警服務

+1

http://developer.android.com/reference/android/app/AlarmManager.html –

回答

2

這是如何實現的警報經理。但是你也需要閱讀關於android中的Calendar對象。你

String alarm = Context.ALARM_SERVICE; 
Calendar calendar = Calendar.getInstance(); 

calendar.set(Calendar.HOUR_OF_DAY, 8);//Just an example setting the alarm for the 8th hour of a day. 
    calendar.set(Calendar.MINUTE, 0); 
calendar.set(Calendar.SECOND,0); 
calendar.set(Calendar.MILLISECOND, 0); 



AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm); 
//This is the intent that is launched when the alarm goes off. 
        Intent intent = new Intent("WAKE_UP"); 

PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0); 



//If the user wants the alarm to repeat then use AlarmManager.setRepeating if they just want it one time use AlarmManager.set(). 

    am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender); 




        } 

還需要註冊一個廣播接收到報警時將其關閉,除了意圖。 您創建BroadCast接收器並將其註冊到清單中以接收來自報警的意圖。 http://www.vogella.de/articles/AndroidServices/article.html

這裏是一個偉大的教程,以幫助您更好地瞭解

+0

@ coder_For_Life22 ..感謝你的迴應...但是你可以告訴我如何關閉警報服務...我必須檢查任何標準...像待決意圖.. 。請幫助... – android

+0

當警報管理器觸發未決意圖時。它並沒有真正運行。它所做的只是一個意圖的激發,例如我上面的「WAKE_UP」,並且在您的清單中您註冊了一個廣播接收器,以便在發生這種情況時啓動。然後您可以有服務或播放音樂或鈴聲。而當你想停止時,你可以使用stopService()。 –

0

關鍵是在待定意圖下使用AlarmManager

mAlarmSender = PendingIntent.getService(AlarmService.this, 
0, new Intent(AlarmService.this, AlarmService_Service.class), 0); 

然後你從當前上下文創建AlarmManager:

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); 

,並安排以前創建掛起的意圖。

am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
         firstTime, 30*1000, mAlarmSender); 

如期AlarmService_Service服務將被調用,或者你可以把另一個意圖就像打開一個特定的活動。

這裏是你如何安排一個報警的完整的例子:AlarmService.java

+0

[AlarmManager.cancel(的PendingIntent)](HTTP: //developer.android.com/reference/android/app/AlarmManager.html#cancel(android.app.PendingIntent))要取消待定意圖 – pablisco

+0

@pablisco ...感謝Ur的迴應...我會盡量讓你知道... – android