alber February 2016

AlarmManager calls the intent service ASAP rather than at the set time

I have a setExact alarm set up in my app and when it reaches that point, instead of activating the alarm at the specified time, it activates it ASAP!

My alarmmanager code

@TargetApi(Build.VERSION_CODES.M)
public void setUpAlarmManager(long time) {

    final Intent intentAlarm = new Intent(this, AlarmService.class);
    final PendingIntent pendingIntent = PendingIntent.getService(this, 100, intentAlarm, PendingIntent.FLAG_ONE_SHOT);
    final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            alarmManager.cancel(pendingIntent);
        }
    }, 1000);
    Log.i(TAG, "setUpAlarmManager: " + time);
}

The handler is just to see if I can cancel the intent through my activity (which also doesn't appear to be working)

My AlarmService

public class AlarmService extends IntentService {

private static final String TAG = "Tag";

// private Ringtone ringtoneAlarm;

public AlarmService() {
    super("AlarmService");
//     ringtoneAlarm = null;
    Log.i(TAG, "AlarmService: ");
}

@Override
protected void onHandleIntent(Intent intent) {
    Log.i(TAG, "onHandleIntent: ");
    Uri alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    Ringtone ringtoneAlarm = RingtoneManager.getRingtone(getApplicationContext(), alarmTone);
    ringtoneAlarm.play();
}

@Override
public void onDestroy() {
    Log.i(TAG, "onDestroy: ");
    super.onDestroy();
//    ringtoneAlarm.stop();
}


}

Can someone help me figure out why my AlarmManager is calling my intent right away instead of at the set time? Basically the intent service just plays an alarm when the alarm activates.

Also should I be using an intentservice for this or a broadcastrece

Answers


Evgeny Maltsev February 2016

To set the alarm to 32 seconds from now, you would do it like this:

private void setAlarmToFuthure(long time){
        Calendar cal_alarm = Calendar.getInstance();
        cal_alarm.add(Calendar.SECOND, (int)time); // Here you add the desired value to the current time (for example: 32 seconds)

        final Intent intentAlarm = new Intent(this, AlarmService.class);
        final PendingIntent pendingIntent = PendingIntent.getService(this, 100, intentAlarm, PendingIntent.FLAG_ONE_SHOT);
        final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);
    }

Post Status

Asked in February 2016
Viewed 2,122 times
Voted 6
Answered 1 times

Search




Leave an answer