gpt4 book ai didi

android - Android 后台服务中的 Realm

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:18 26 4
gpt4 key购买 nike

我在我的 android 应用程序中使用 Realm。我通过 CompletionEvent 收到来自 google drive 的通知,因此我需要在服务中修改我的 Realm 数据库。

我得到的异常是:

java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

我已经通过以下方式在我的应用程序类中设置了我的默认配置:

RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(getApplicationContext())
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);

在我的服务的 onCreate 中,我得到了这样的 Realm 实例:

mRealm = Realm.getDefaultInstance();

然后我在服务中使用这个 Realm 实例:

mRealm.executeTransaction(realm -> {
DocumentFileRealm documentFileRealm = realm.where(DocumentFileRealm.class)
.equalTo("id", documentFileId)
.findFirst();
documentFileRealm.setDriveId(driveId);
});

但是当执行最后一个时,应用会启动 IllegalStateException。我不知道为什么。我不确定它是否与我在我的 android list 中声明服务的方式有关,所以我把它留在这里:

<service android:name=".package.UploadCompletionService" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.drive.events.HANDLE_EVENT"/>
</intent-filter>
</service>

是否可以从后台服务调用 Realm?我使用它的方式有什么问题?

提前致谢。

最佳答案

在 IntentService 中,您应该像对待 AsyncTask 的 doInBackground 方法一样对待 onHandleIntent 方法。

因此它在后台线程上运行,您应该确保在 finally block 中关闭 Realm。

public class PollingService extends IntentService {
@Override
public void onHandleIntent(Intent intent) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
// go do some network calls/etc and get some data
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.createAllFromJson(Customer.class, customerApi.getCustomers()); // Save a bunch of new Customer objects
}
});
} finally {
if(realm != null) {
realm.close();
}
}
}
// ...
}

onCreate 在 UI 线程上运行,因此您对 Realm 的初始化发生在不同的线程上,这是不行的。

关于android - Android 后台服务中的 Realm ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211431/

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