【问题标题】:Using ContentProvider from an IntentService从 IntentService 使用 ContentProvider
【发布时间】:2014-08-12 17:21:08
【问题描述】:

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

我计划在我的应用程序中使用 IntentService 在手机完成启动时重新安排一些警报,但首先我需要从 ContentProvider 中提取一些数据。根据theselinks,我可以通过注册一个 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);
}

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

调试,我发现从来没有调用过 ScheduleServie.OnLoadComplete 方法。首先调用 onCreate 方法,然后调用 onHandleIntent,最后调用 onDestroy。我做错了吗?

【问题讨论】:

    标签: android android-contentprovider android-broadcast android-intentservice


    【解决方案1】:

    根据IntentService 文档:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多