使用IntentService中的ContentProvider

por*_*cho 1 android android-contentprovider android-broadcast android-intentservice

我在使用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);
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}}
Run Code Online (Sandbox Code Playgroud)

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

ian*_*ake 7

根据IntentService文档:

要使用它,请扩展IntentService并实现onHandleIntent(Intent).IntentService将接收Intents,启动工作线程,并根据需要停止服务.

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

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