Ankur Jain Ankur Jain - 1 year ago 63
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 Source

I am using this code and it is working perfectly:


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.set(Calendar.HOUR_OF_DAY, 18);
        wakeupcall.set(Calendar.MINUTE, 30);

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

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

            al.set(AlarmManager.RTC_WAKEUP,_alarm, fintent);
        else if (Build.VERSION_CODES.KITKAT <= SDK_INT  && SDK_INT < Build.VERSION_CODES.M) {
        else if (SDK_INT >= Build.VERSION_CODES.M) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download