gpt4 book ai didi

android - 从 IntentService 使用 ContentProvider

转载 作者:行者123 更新时间:2023-11-29 14:37:48 25 4
gpt4 key购买 nike

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

我计划在我的应用程序中使用 IntentService 在手机完成启动时重新安排一些警报,但首先我需要从 ContentProvider 中提取一些数据。根据these links ,我可以通过注册 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。我做错了什么吗?

最佳答案

根据 IntentService文档:

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

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

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

关于android - 从 IntentService 使用 ContentProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com