Skip to content

Instantly share code, notes, and snippets.

@RanjitPati
Last active August 9, 2019 13:38
Show Gist options
  • Save RanjitPati/428e6c7ac4f281af3103e63bcd15afa3 to your computer and use it in GitHub Desktop.
Save RanjitPati/428e6c7ac4f281af3103e63bcd15afa3 to your computer and use it in GitHub Desktop.
public class AnalyticsService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
//let's update the analytics stuff when the job starts
//you can skip this method if it seems complex. we will understand this in GreenDAO tutorials
updateAnaliticsData();
//return false if the task is small and it will finish inside this onStartJob method or else true if your task is bigger
//I am returning true because I am running a network operation which will use a background thread
return true;
}
private void updateAnaliticsData() {
//Here I am getting the analytics data from my local database and sending to server.
//skip this part if it's looking complex
final AnalyticsRestApiClient client = new AnalyticsRestApiClient();
final List<ActivityData> events = DatabaseContext.getInstance().getDaoSession().getActivityDataDao().loadAll();
if (events.size() > 0) {
new AsyncTask<Void, Void, RestApiResult>() {
RestApiResult result = null;
@Override
protected RestApiResult doInBackground(Void... voids) {
try {
result = client.updateAnalytics(LocationSessionUtils.getConsumerLocationInfo(), events);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(RestApiResult pResult) {
//Here I am cheking the result from server, if the result is perfect then I am deleting the local data.
if (result != null && result.getStatus() != null && !result.getStatus().isError()) {
DatabaseContext.getInstance().getDaoSession().getActivityDataDao().deleteAll();
Log.e("JOB SCHEDULER SERVICE", "job started and continued properly");
}
}
}.execute();
}
}
@Override
public boolean onStopJob(JobParameters params) {
Log.e("JOB SCHEDULER SERVICE", "job stopped");
//return false when you don't want to restart the job again after stopping
//or else return true if you want to retry
//I am returning true, because I want to restart the task after stopping
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment