在IntentService和AsyncTask(Android)之间使用共享代码时,Realm`从错误的线程访问`错误

Roc*_*Lee 16 multithreading android realm android-asynctask android-intentservice

我有一些代码可以下载"当前"对象的JSON.但是,每当警报响起时(当应用程序没有运行任何UI时),以及应用程序运行时的AsyncTask,IntentService都需要调用相同的代码.

但是,我得到一个错误说Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.但是,我不明白这个堆栈跟踪是如何或为什么在另一个线程上.

我能够通过复制所有共享代码并将其直接粘贴到DownloadDealService的onHandleIntent方法中来消除错误,但它非常草率,我正在寻找一个不需要复制代码的更好的解决方案.

如何在不重复代码的情况下摆脱此错误?谢谢.

public class DownloadDealService extends IntentService
{
    ...
    @Override
    protected void onHandleIntent(Intent intent)
    {
        Current todaysCurrent = Utils.downloadTodaysCurrent(); //<--- included for background info
        String dateString = Utils.getMehHeadquartersDate(); //(omitted)
        Utils.onDownloadCurrentCompleteWithAlarm(todaysCurrent, dateString); //<------ calling this...
    }
}

public class Utils
{
    // ...other methods ommitted...

    //This method is not in the stack trace, but I included it for background information.
    public static Current downloadTodaysCurrent()
    {
        //Set up Gson object... (omitted)
        //Set up RestAdapter object...?(omitted)
        //Set up MehService class...?(omitted)

        //Download "Current" object from the internet.
        Current current = mehService.current(MehService.API_KEY);
        return current;
    }

    //Included for background info- this method is not in the stack trace.
    public static void onDownloadCurrentComplete(Current result, String dateString)
    {
        if(result.getVideo() == null)
        {
            Log.e("HomePage", "Current was not added on TaskComplete");
            return;
        }
        remainder(result, dateString);
    }

    public static void onDownloadCurrentCompleteWithAlarm(Current result, String dateString)
    {
        //Set alarm if download failed and exit this function... (omitted)

        remainder(result, dateString);//<------ calling this...
        Utils.sendMehNewDealNotification(App.getContext());
    }

    public static void remainder(Current result, String dateString)
    {
        Realm realm = RealmDatabase.getInstance();

        //Add "Current" to Realm
        Current current = Utils.addCurrentToRealm(result, realm); //<------ calling this...
    }

    public static Current addCurrentToRealm(Current current, Realm realm)
    {
        realm.beginTransaction(); //<---- Error is here
        Current result = realm.copyToRealmOrUpdate(current);
        realm.commitTransaction();
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

E/AndroidRuntime: FATAL EXCEPTION: IntentService[DownloadDealService]
Process: com.example.lexi.meh, PID: 13738
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
    at io.realm.Realm.checkIfValid(Realm.java:191)
    at io.realm.Realm.beginTransaction(Realm.java:1449)
    at com.example.lexi.meh.Utils.Utils.addCurrentToRealm(Utils.java:324)
    at com.example.lexi.meh.Utils.Utils.remainder(Utils.java:644)
    at com.example.lexi.meh.Utils.Utils.onDownloadCurrentCompleteWithAlarm(Utils.java:635)
    at com.example.lexi.meh.Home.DownloadDealService.onHandleIntent(DownloadDealService.java:42)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.os.HandlerThread.run(HandlerThread.java:61)
Run Code Online (Sandbox Code Playgroud)

我有一个AsyncTask也可以调用其中的一些Utils方法:

public class DownloadAsyncTask extends AsyncTask<Void, Integer, Current>
{
    // ... (more methods ommitted)...

    protected Current doInBackground(Void... voids)
    {
        return Utils.downloadTodaysCurrent(); //<---- shared Utils method
    }
}

//Async class's callback in main activity:
public class HomePage extends AppCompatActivity implements DownloadAsyncTaskCallback, DownloadAsyncTaskGistCallback<Current, String>
{
    // ... (more methods ommitted)...

    public void onTaskComplete(Current result, String dateString)
    {
        Utils.onDownloadCurrentComplete(result, dateString);
    }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*rra 20

[更新]基于附加信息

RealmDatabase.getInstance()返回在主线程上创建的Realm实例.这个实例用在IntentService的线程上.导致崩溃的原因.

Realm实例不能用于除创建它们之外的任何其他线程.


您无法在线程之间传递Realm对象.你可以做的是传递对象的唯一标识符(即@PrimaryKey),然后通过另一个线程上的id获取对象.像这样:realm.where(YourRealmModel.class).equalTo("primaryKeyVariable",id).findFirst().

有关更多详细信息,请查看Realm的官方文档和示例:

  • 我怀疑你是在RealmDatabase类中对Realm实例进行一些自定义缓存.这导致你从不同的线程调用它,而不是你获得它的原始线程.只需使用Realm.getDefaultInstance(). (2认同)
  • 我能够通过在我的`IntentService`中使用`Realm.getInstance(this)`来解决这个问题,并将其传递给Util方法使用(因为这些方法无法访问线程上下文).所以现在,Util方法可以由多个线程使用,每个线程都有一个正确的Realm实例. (2认同)