This can be implemented via Android Service.
Benefits of Android Service with START_STICKY
- Android will take responsibility to start your service again if stopped by any reason.
- Below service runs on worker thread which will never hang your app.
- get data api will never be call twice if in process. (flag maintained)
I implemented this class in my location tracking app. which you can just paste and use.
package in.kpis.tracker.projectClasses.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by KHEMRAJ on 1/24/2018.
*/
public class SyncLocationServiceSample extends Service {
public String TAG = "SyncLocationService";
private Thread mThread;
ScheduledExecutorService worker;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
if (worker == null) worker = Executors.newSingleThreadScheduledExecutor();
if (mThread == null || !mThread.isAlive()) {
mThread = new Thread(new Runnable() {
@Override
public void run() {
syncLocationAPI();
if (worker != null) {
// 60 * 1000 is 60 second, change it as your requirement.
worker.schedule(this, 60 * 1000, TimeUnit.MILLISECONDS);
}
}
});
mThread.start();
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopThread();
}
boolean apiCalling = false;
private synchronized void syncLocationAPI() {
if (apiCalling) return;
// do your api call here.
// make apiCalling true when you call api, and apiCalling false when response come
}
private void stopThread() {
worker = null;
if (mThread != null && mThread.isAlive()) mThread.interrupt();
}
}
Things to be consider
You will start this service with an device boot complete receiver. How to make boot complete receiver. Let me know if you need help for starting service.