Ankur Jain Ankur Jain - 22 days ago 9
Android Question

Intent Service Time Interval Not maintained

I have created an intent service which should send data to the server at a userdefined interval, but in my case time, the interval is not maintained correctly by alarm manager. Can u guide where I m doing error. I want to run the service while the device in sleep or idle mode too. Here is my code.

public void sosalarmson() {
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, AlarmReceiver.receivercode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), Integer.parseInt(userdefinedinterval) *60* 1000, pendingIntent);
Toast.makeText(FinalSettings.this, "alarm On", Toast.LENGTH_SHORT).show();
}


Ideally, if I give user input as 15, so alarm should send intent at 15 mins, whereas it is sending at 10mins.

Answer

I am using this code and it is working perfectly:

define:

final int SDK_INT = Build.VERSION.SDK_INT;
AlarmManager al;
PendingIntent fintent;
Intent notif;

i am directly start service using alarm manager._alarm is your predefined interval.

long _alarm;

        Calendar now = Calendar.getInstance();
        Calendar wakeupcall = Calendar.getInstance();
        wakeupcall.setTimeInMillis(System.currentTimeMillis());
        wakeupcall.set(Calendar.HOUR_OF_DAY, 18);
        wakeupcall.set(Calendar.MINUTE, 30);

        if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis())
            _alarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
        else
            _alarm=wakeupcall.getTimeInMillis();

al = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        notif= new Intent(this,TestNotifyService.class);
        fintent = PendingIntent.getService(this,0,notif,0);

if (SDK_INT < Build.VERSION_CODES.KITKAT) {
            al.set(AlarmManager.RTC_WAKEUP,_alarm, fintent);
        }
        else if (Build.VERSION_CODES.KITKAT <= SDK_INT  && SDK_INT < Build.VERSION_CODES.M) {
            al.setExact(AlarmManager.RTC_WAKEUP,_alarm,fintent);
        }
        else if (SDK_INT >= Build.VERSION_CODES.M) {
            al.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,_alarm,fintent);
        }
Comments