1

我在使用 IntentService 中的 ContentProvider 时遇到问题。

我计划在我的应用程序中使用 IntentService 在手机完成启动时重新安排一些警报,但首先我需要从 ContentProvider 中提取一些数据。根据这些 链接,我可以通过注册 BroadcastReceiver 并从那里启动 IntentService 来实现。这就是我所做的:

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);
}

调度服务.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();
    }
}}

调试时,我发现从未调用过 ScheduleServie.OnLoadComplete 方法。首先调用 onCreate 方法,然后调用 onHandleIntent,最后调用 onDestroy。难道我做错了什么?

4

1 回答 1

7

根据IntentService文档:

要使用它,请扩展 IntentService 并实现 onHandleIntent(Intent)。IntentService 将接收 Intent,启动工作线程,并酌情停止服务。

这意味着一旦handleIntent()完成,服务就会停止。

由于handleIntent()已经在后台线程上,您应该使用同步方法来加载数据,例如ContentResolver.query()而不是异步方法,例如CursorLoader. 确保在方法完成之前关闭Cursor返回的 by !query

于 2014-08-12T17:24:59.743 回答