Android领域不正确的线程 [英] Android realm incorrect thread
本文介绍了Android领域不正确的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个服务,其中之一是生产者(将对象保存到领域),其他则从领域读取此对象并将其发送到计划任务中的REST服务.
I have 2 Services, one of them is a producer (saving objects to realm), and other reading this objects from realm and sending them to REST service in scheduled tasks.
我的例外:
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
服务1:
this.scheduler.schedule("*/2 * * * *", new Runnable() {
public void run() {
List<Location> locations = dataStore.getAll(Location.class);
for(Location l : locations) {
try {
serverEndpoint.putLocation(l);
l.removeFromRealm();
} catch (SendingException e) {
Log.i(this.getClass().getName(), "Sending task is active!");
}
}
}
});
服务2:
private LocationListener locationListener = new android.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
TLocation transferLocation = new TLocation();
transferLocation.setLat( location.getLatitude() );
transferLocation.setLng(location.getLongitude());
dataStore.save(transferLocation);
}
}
数据存储实现:
public void save(RealmObject o) {
this.realm.beginTransaction();
this.realm.copyToRealm(o);
this.realm.commitTransaction();
}
public <T extends RealmObject> List<T> getAll(Class<T> type) {
return this.realm.allObjects(type);
}
推荐答案
对于每个线程,您应该使用自己的Realm实例:
You should use own instance of Realm for each thread:
// Query and use the result in another thread
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Get a Realm instance for this thread
Realm realm = Realm.getInstance(context);
...
来自Realm文档:
跨线程使用Realm的唯一规则是要记住 Realm, RealmObject或RealmResults 实例不能跨线程传递.
The only rule to using Realm across threads is to remember that Realm, RealmObject or RealmResults instances cannot be passed across threads.
这篇关于Android领域不正确的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文