Turbozanik Turbozanik - 1 month ago 9
Android Question

Can you explain me how the IntentService works

I got an

IntentService
that execute CRUD operations, i am starting
IntentService
when my app starts to update data, when data is updated i need to start activity that actualy shows that data.

But as i see now,
IntentService
starts my code in a separated process, that actualy finishes after my activity is created, so i have empty activity. Can i fix this? Or standart
Service
is the only way?

@Override
protected void onHandleIntent(Intent intent) {
Log.e("action",intent.getStringExtra(Utils.INTENT_SERVICE_INVOKE));
ResultReceiver resultReceiver = intent.getParcelableExtra(Utils.RECEIVER);
switch (intent.getStringExtra(Utils.INTENT_SERVICE_INVOKE)){
case Utils.LOAD_All_DATA:{
loadActivities();
loadPersons();
loadPictureData();
Log.e("order","forth");
resultReceiver.send(Utils.TASK_FINISHED,new Bundle());
// Intent broadcastIntent = new Intent();
// broadcastIntent.setAction(Utils.LOAD_All_DATA);
// sendBroadcast(broadcastIntent);
break;
}
case Utils.READ_ACTIONS_DATA:{
readActionData();
break;
}
case Utils.READ_PERSONS_DATA:{
readPersonsData();
break;
}
case Utils.READ_ACTION_BY_ID:{
readActionDataById(intent);
break;
}
}
}

Answer

IntentService does not start in separate process by default. It is a regular Service with the addition of logic that delegates execution of work to a single background thread and stops the service once all incoming Intents had been handled.

You want to do the following:

  1. Perform data update from the web server
  2. Notify once update completed
  3. Get a reference to updated data from Activity

Your options are (from the top of my head):

  1. Use standard android Service which can be both started and bound. Start this Service when update required, send notification when update completes and bind the Service from Activity in order to get the data.
  2. Implement some in-memory cache which is neither tied to IntentService, nor to Activity. For example: implement DataManager class and instantiate it in Application. Both the IntentService and Activity can get a reference to Application, therefore they will be able to get a reference to DataManager object. IntentService will write the data into it, and Activity will read this data later
  3. Implement data cache SQLite. This approach is very similar to #2 above, but data is not stored in memory, but written into SQLite database.

The easiest amongs the three options above is #2. Furthermore, if you go with #2 then it will be relatively easy to migrate to #3 if such a need arises (which is the best for "data heavy" apps).