在IntentService
内部,应用程序可能处于活动或非活动状态,在调用onHandleIntent
时,我放置了下面的代码。这是我将数据存储到realm中的地方。
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (AppItem item : items) {
AppItem item2 = realm.createObject(AppItem.class, UUID.randomUUID().toString());
item2.mName = item.mName;
item2.mCount = item.mCount;
item2.mUsageTime = item.mUsageTime;
}
}
});
} finally {
if (realm != null) {
realm.close();
}
}
然后我试图在AsyncTask
中的onPostExecute
中访问它,在doInBackground
中,我获取RealmResults<AppItem>
,然后将其存储到List <AppItem>
中并将其发送到放置此代码的onPostExecute
。 这里的appItems
是ReamObject。
Realm backgroundRealm = Realm.getDefaultInstance();
backgroundRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (AppItem item : appItems) {
//getting error here if (item.mUsageTime <= 0) continue;
mTotal += item.mUsageTime;
item.mCanOpen = mPackageManager.getLaunchIntentForPackage(item.mPackageName) != null;
}
}
});
我已经使用executeTransactionAsync
进行了两次操作,但仍然出现以下错误。
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.