4

Hi i want to update service running in background on every 15 minutes interval on specifically on the 15 minutes current time basis.

Service:

public class UpdateService extends IntentService {

    public UpdateService() {
        super("UpdateService");
    }

    // will be called asynchronously by Android
    @Override
    protected void onHandleIntent(Intent intent) {
        updateFragmentUI();
    }


    private void updateFragmentUI() {
        this.sendBroadcast(new Intent().setAction("UpdateChart"));
    }
}
Shanmugapriyan M
  • 301
  • 5
  • 17

3 Answers3

1

Use Alarm Manger or Job Scheduler to start Service Take a look at this link..

How to start Service using Alarm Manager in Android?

for you i will suggest to use setExact instead of setRepeating. Here is the code...

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else
    am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);

Remember setExact does not provide repeating feature so every time you have to set it from your service again... and first time from your activity with 10 min delay. and in service with 15 min delay(According to your use case).

Community
  • 1
  • 1
Techierj
  • 131
  • 9
1

With Jobscheduler you can use .setPeriodic(int millis)

Pablo Cegarra
  • 20,955
  • 12
  • 92
  • 110
-1

I had the same issue, I used recursive function with Handler of postDelay.

Solution:

public class UpdateService extends Service {

Handler handler = new Handler();

public UpdateService() {
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

  handler.postDelayed(new Runnable() {
    public void run() {    

                    /*
                     * code will run every 15 minutes
                      */

                    handler.postDelayed(this, 15 * 60 * 1000); //now is every 15 minutes
                   }

                }, 0); 

    return START_STICKY;
   }
}
W4R10CK
  • 5,502
  • 2
  • 19
  • 30
  • It will work for every 15 minutes but if i start a service at 12:02 AM it should be update 12:15 only not 12:17 and then every 15 min interval it should update. – Shanmugapriyan M Mar 26 '17 at 08:52
  • Your question is to run your service every 15 minutes, if you want to run something on specific time. Use Alarm Manager – W4R10CK Mar 26 '17 at 09:34