2017-06-04 63 views
0

我有一个导致崩溃的领域线程,我不知道为什么这是不被允许的,或者如何绕过它。这里是发生了什么事情的一些示例代码:IntentService领域 - 线程创建崩溃

public class UploadPostService extends IntentService { 

public UploadPostService() { 
    super("UploadPostService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 

    String uniqueCode = intent.getStringExtra("uniqueCode"); 

    OurApi api = OurApi.build(this, Application.apiRoot); 

    final Realm r = Realm.getDefaultInstance(); 

    final RealmResults<Post> thePosts = r.where(Post.class) 
      .equalTo("post.code", uniqueCode) 
      .findAll(); 

    if (thePosts != null && thePosts.size() > 0) { 
     for (final Post post : thePosts) { 
      api.uploadMedia(paramsToUpload, new Callback<Post>() { 
       @Override 
       public void success(Post postResponse, Response response) { 
        if (post.isValid()) { 
         r.beginTransaction(); 
         post.setAField(blah); // CRASHES HERE 
         r.commitTransaction(); 
        } 
       } 
     } 
    etc... 

的API与改造通话结束后,它崩溃的任何字段的设置与异常的“邮报”对象:

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

我很好奇最干净的解决方案应该是什么?假设回调是在一个不同的线程比IntentService一个..我需要更新实际的邮政,它不让我;我尝试创建单独的Realm实例,但它不会让我更新Post,因为它不是(显然)从同一实例查询的。

这对我们的代码至关重要,所以我有点难住。预先感谢您的任何建议!

回答

0

这是因为IntentService在后台线程上运行,但是您的api回调会尝试在UI线程上运行,这意味着它与您的RealmResults所属的Realm实例已打开的线程位于不同的线程。

另外,你打算在UI线程上写入Realm,这是不鼓励的。使用同步API调用IntentService。在改造中,它是call.execute()

我也希望你能在finally块中关闭Realm实例!