c0tonet
c0tonet

Reputation: 23

Using ContentProvider from an IntentService

I'm having problems using a ContentProvider from an IntentService.

I plan to use an IntentService in my app to reschedule some alarms when the phone finishes booting up, but first I need to pull some data from the ContentProvider. According to these links, I'd be able to that by registering a BroadcastReceiver and firing up the IntentService from there. That's what I did:

OnBootReceiver.java

public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent scheduleServiceIntent = new Intent(context, ScheduleService.class);
    context.startService(scheduleServiceIntent);
}

ScheduleService.java

public class ScheduleService extends IntentService implements Loader.OnLoadCompleteListener<Cursor> {

private AlarmManager alarmManager;

@Override
public void onCreate() {
    super.onCreate();

    alarmManager = (AlarmManager) this.getApplicationContext().getSystemService(Context.ALARM_SERVICE);

}

@Override
protected void onHandleIntent(Intent intent) {
    String[] projection = new String[] {
    Contract._ID,
            Contract.START_TIME,
    Contract.DATE,
            Contract.NAME,
            Contract.TYPE};

    mCursorLoader = new CursorLoader(this, MyContentProvider.MyURI,
            projection, selection, selectionArgs, SOME_ID);
    mCursorLoader.registerListener(ID, this);
    mCursorLoader.startLoading();
}

@Override
public void onLoadComplete(Loader<Cursor> cursorLoader, Cursor cursor) {

    //pull data from the Cursor and set the alarms
}

@Override
public void onDestroy() {
    super.onDestroy();

    if (mCursorLoader != null) {
        mCursorLoader.unregisterListener(this);
        mCursorLoader.cancelLoad();
        mCursorLoader.stopLoading();
    }
}}

Debugging, I've found out that the ScheduleServie.OnLoadComplete method is never called. First, the onCreate method is called, then onHandleIntent, and finally onDestroy. Am I doing something wrong?

Upvotes: 1

Views: 940

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199870

Per the IntentService documentation:

To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

This means that as soon as handleIntent() is finished, the service is stopped.

As handleIntent() is already on a background thread, you should use the synchronous methods to load data such as ContentResolver.query() rather than asynchronous methods such as CursorLoader. Make sure you close the Cursor returned by query before your method completes!

Upvotes: 7

Related Questions