如何在n天后停止我的报警服务?

时间:2011-09-14 09:04:03

标签: android calendar alarmmanager android-pendingintent

我正在尝试在指定日期启动警报作为用户输入,我需要在某些'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();  
} 

2 个答案:

答案 0 :(得分:0)

AlarmManager.cancel(..)取消匹配意图。出于匹配intent.filterEquals(..)的目的使用。确保在装箱警报时使用的意图与用于取消警报的意图相匹配。

答案 1 :(得分:0)

您需要设置另一个闹钟以在功能关闭时执行该功能。