2011-09-14 61 views
0

我試圖在用戶輸入的指定日期開始鬧鐘,我需要在一段時間後停止鬧鐘。在這裏,我可以在指定的一天開始報警。但我無法阻止它。所以請任何人幫助我。如何在n天后停止報警服務?

private void Dailyalarm1(String time, String date) 
{ 

    System.out.println(time); 
    String min = time.substring(3, 5); 
    System.out.println(min); 
    int min1 = Integer.parseInt(min); 

    String hour = time.substring(0, 2); 
    System.out.println(hour); 
    int hour1 = Integer.parseInt(hour); 

    System.out.println(date); 
    String day = date.substring(0, 2); 
    System.out.println("date id: "+day); 
    int day1 = Integer.parseInt(day); 

    EditText days = (EditText)findViewById(R.id.days); 
    int numOfDays = Integer.parseInt(days.getText().toString()); 

    Intent myIntent = new Intent(this, MyAlarmService.class); 

    pendingIntent = PendingIntent.getService(this,(int) System.currentTimeMillis(), myIntent, 0); 
    System.out.println("alarm service"); 

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 

    Calendar cal = Calendar.getInstance(); 

    cal.set(Calendar.HOUR_OF_DAY, hour1); 
    cal.set(Calendar.MINUTE, min1);  
    cal.set(Calendar.SECOND, 0); 
    cal.set(Calendar.MILLISECOND, 0); 
    cal.set(Calendar.DATE, day1); 
    System.out.println("start day is:"+ cal.get(Calendar.DATE)); 

    System.out.println("after alarm service starts date is "+ cal.get(Calendar.DATE)); 
    System.out.println("number of days: "+numOfDays); 


    System.out.println("Current date : " + (cal.get(Calendar.MONTH) + 1) + "-" 
      + cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.YEAR)); 

    System.out.println("after caculating end date alarm service stop date is "+ cal.get(Calendar.DATE)); 

    Calendar calender = Calendar.getInstance(); 
    calender.set(Calendar.HOUR_OF_DAY, hour1); 
    calender.set(Calendar.MINUTE, min1);  
    calender.set(Calendar.SECOND, 0); 
    calender.set(Calendar.MILLISECOND, 0); 
    calender.add(Calendar.DATE, numOfDays); 

    do 
    { 
     pendingIntent = PendingIntent.getService(this,(int) System.currentTimeMillis(), myIntent, 0); 

     AlarmManager alarmManagerStop = (AlarmManager)getSystemService(ALARM_SERVICE); 
     alarmManagerStop.cancel(pendingIntent); 
     Toast.makeText(this, "alarm cancel", Toast.LENGTH_SHORT).show(); 
    } 
    while(cal.equals(calender)); 


    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24*60*60*1000, pendingIntent); 

    Toast.makeText(this, "alarm set", Toast.LENGTH_SHORT).show(); 

    System.out.println("after alarm service set repeat"); 

    Toast.makeText(this, "Start Daily Alarm", Toast.LENGTH_LONG).show(); 
} 

回答

0

AlarmManager.cancel(..)取消匹配意圖。爲了匹配的目的,使用了intent.filterEquals(..)。確保您在裝箱報警時使用的意圖符合您用來取消報警的意圖。

0

您將需要設置另一個鬧鐘,以便在功能關閉時執行功能。