I have to call multiple services in background for a project in android app. In each services i have to call separate web service and get some data and process it with local sqlite database. I am able to call each service separately and can manipulate its result with local database. But not able to call all services in a sequence. my code is as below:
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Timer timer = new Timer();
final SyncTableUsers syncUserObj = new SyncTableUsers(LocalService.this);
final SyncTableVehicles syncVehicleObj = new SyncTableVehicles(this);
final SyncTableLicenses syncLicenseObj = new SyncTableLicenses(this);
final SyncTableTags syncTagObj = new SyncTableTags(this);
final SyncTableTagMappings syncTagMapObj = new SyncTableTagMappings(this);
final SyncTableAddresses syncAddressObj = new SyncTableAddresses(this);
final SyncTableDispatches syncDispatchObj = new SyncTableDispatches(this);
final SyncEditCompany syncCompanyObj = new SyncEditCompany(LocalService.this);
final SyncEditVehicle syncEditVehicleObj = new SyncEditVehicle(LocalService.this);
final SyncEditUser syncEditUserObj = new SyncEditUser(this);
final SyncVehicleLog vLogObj = new SyncVehicleLog(LocalService.this);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
syncUserObj.syncUserData();
syncVehicleObj.syncVehicleData();
syncLicenseObj.syncLicensesData();
syncTagObj.syncTagData();
syncTagMapObj.syncTagMappingData();
syncAddressObj.syncAddressData();
syncDispatchObj.syncDispatchData();
syncCompanyObj.syncCompanyData();
syncEditVehicleObj.syncVehicleData();
syncEditUserObj.syncUserData();
Log.i("TAG", "LogId After insert values ");
}
}
};
timer.scheduleAtFixedRate(timerTask, 10000, 180000); call after every
3 minute
super.onStart(intent, startid);
syncUserData is a method, which call web service.
Use Intent Service to execute your tasks in sequence. Check out the below link for details
https://developer.android.com/reference/android/app/IntentService.html
I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask.
It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.