0

I have an Activity that has a fragment which is full screen RecyclerView. The fragment implements LoaderManager.LoaderCallbacks<Cursor>.

I have an IntentService that goes out and fetches data from an API, deletes any existing data in the local SQLite database, and then stores the new data all via a content provider.

The Loader then Loads whatever data was put into SQLite into the RecyclerView.

My question is: Where would be the most efficient place to put my code to fire off the IntentService?

Just wondering if there are any conflicts that could arise if placed in an inappropriate place.

Currently, I have it as the last lines in OnCreate() in the Activity:

// Fire off service to get data
Intent i = new Intent(this, MyService.class);
startService(i);

Other places I was considering putting it:

  • In the OnCreate() in the fragment.
  • In the OnActivityCreated() in the fragment.
Micro
  • 10,303
  • 14
  • 82
  • 120

2 Answers2

1

In my opinion, running it in onCreate of your activity is just fine, however in this case, your RecyclerView may present outdated contents to the user. So you should somehow notify your RecyclerView from inside that IntentService and make it to re-query the database.

Running that service in onCreate of that fragment or OnActivityCreated() wouldn't give you any performance gains.

To bring a better user experience to your users, I would suggest you that use pull-to-update libraries to fire off that service and update the list whenever the user drags it down. Just like Instagram app.

frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Cool. The reason I set things up the way I did is so that, just like the Instagram app, if you open the app and have no network, you will still see the results of the last time you opened the app (albeit you will get a toast notification saying "Couldn't refresh results"). So it is ok if those outdated contents are presented to the user in that case. Better than looking at a blank screen at least. And you totally read my mind with using pull-to-update with this set up =) My exact intention. – Micro Feb 17 '16 at 10:28
0

First, I would like you to take a look at this answer in SO that also has links to android documentations.

Also from the documentations, an IntentService has few limitations:

An IntentService has a few limitations:

It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.

Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished.

An operation running on an IntentService can't be interrupted.

However, in most cases an IntentService is the preferred way to perform simple background operations.

Community
  • 1
  • 1
blackorange
  • 441
  • 3
  • 8