Dexter
Dexter

Reputation: 1750

CursorLoader to query data inside IntentService implementation

I have an intent-service which runs practically, infinitely, till a static kill Boolean is set to true or some specific condition calls stopSelf(). (is this a good idea ?) My service depends on querying a content-provider. Now I did not want to "poll" the provider for changes, so I tried

getContentResolver().registerContentObserver(uri, false, contentObserver);

I define my ContentObserver like this :

private final ContentObserver contentObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            if(kill) {
                Log.i("Downloader", "Unregister observer");
                getContentResolver().unregisterContentObserver(contentObserver);
                return;
            }
            //Must submit to a thread else, UI gets blocked
            executor.execute(updater);
        }
    };

private final Executor executor = Executors.newSingleThreadExecutor();

"updater" is simple Runnable which reQueries the object I'm observing.

So far, this model seems to be working. When the URI im observing gets deleted I exit my service using stopSelf(). Basically this service is started to monitor a particular URI for changes. The inbuilt queuing of intent service really works out for me. I have 2 questions :

  1. Is there a better way to supply a handler than using the main Looper ? If I use the handler of my service's thread all the "messages" are delivered to onChange after my service dies (if i do not unregister the observer)
  2. Is this model sensible ?

Upvotes: 0

Views: 188

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007474

is this a good idea ?

IMHO, no. Use a regular Service and manage your own background thread. Then use stopService(), or a message delivered to the service via startService(), instead of "a static kill Boolean".

Is there a better way to supply a handler than using the main Looper ?

Use a regular Service and fork your own HandlerThread, then use its Looper. Then you can get rid of the separate Executor, and you still do not have to worry about tying up the main application thread, as you do with the main thread's Looper.

Upvotes: 0

Related Questions