开发者

how to stop my alarm service after 2 days at particular time?

开发者 https://www.devze.com 2023-04-04 05:26 出处:网络
Below is my code for setting repeat alarm for daily. Now i need to stop my alarm after 2 days. I tried to stop alarm after adding 2 days but it is not working . Please anyone help me.

Below is my code for setting repeat alarm for daily. Now i need to stop my alarm after 2 days. I tried to stop alarm after adding 2 days but it is not working . Please anyone help me.

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

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

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hour1);
    calendar.set(Calendar.MINUTE, min1);
    calendar.set(Calendar.SECOND, 0);   

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pe开发者_JAVA技巧ndingIntent);

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

     //trying to cancel after 2 days
    // add days to current date using Calendar.add method 

    calendar.add(Calendar.DATE, 2);       
    pendingIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0);
    AlarmManager alarmManagerstop = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManagerstop.cancel(pendingIntent);     


here you pass the System time in milisecond in the 2nd parameter.

PendingIntent.getService(this, (int) System.currentTimeMillis(), myIntent, 0);

as in the 2nd parameter was the request code was pass so you have to do something like this.

private static int REQUEST = 1;

you have to keep this request code for each alarm you are set. Note if you pass this request code with same value then it'll be override your alarm. so you have to pass the unique request code.

For stop the alarm same request code was needed to find that PendingIntent object and pass to the alarm.cancel method like this way

private static int REQUEST = 1;
PendingIntent.getService(this, REQUEST, myIntent, 0);
AlarmManager alarmManagerstop = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManagerstop.cancel(pendingIntent); 

and as you used System milisecond that was change in every milisecond so that request code also change frequently. To use this milisecond you can store in any static variable after that you can use same value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号