Android Realm - Accessing Realm Object from Service
<p>I have a realm object that is created in my activity. I need to be able to access this object within a service that I created. However I'm getting the error when creating the Realm object within the service</p>

<pre><code>        mRealm = Realm.getInstance(getApplicationContext());
</code></pre>

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

<p>Now I understand this means that because the realm object was created on my activity, I cannot access it from a background thread. However, I'm not finding an easy way around this other than creating my own custom Handler Thread but that just seems like a clunky way of doing it. </p>

<p>Am I missing something here or is there really no better way to be able to access Realm object from within different threads?</p>

<p><strong>Update:</strong></p>

<p>I dug a little deeper to figure out that in an IntentService, the onHandleIntent method runs in a separate thread than other methods within the class. Therefore, I cannot create a class level Realm instance and be able to interact with that inside and outside of the onHandleIntent method. That is what was causing the thread exception. Aside from creating a separate instance of Realm in each method I need to access the object and retrieving it over and over again, I think Ilya Tretyakov's answer will be best. I can copy the object from realm in my constructor and then work with it throughout the life of the service. Any methods that need to write back to the Realm object will need to instantiate their own Realm instance within that method.</p>