Android background area

I am using Realm in my Android app. I get a notification from a Google drive through CompletionEvent, so I need to change the area database in the service.

An exception I get:

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

I set my default configuration in my application class as follows:

RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(getApplicationContext())
            .deleteRealmIfMigrationNeeded()
            .build();
Realm.setDefaultConfiguration(realmConfiguration);

And in onCreate from my service, I get my Realm instance as follows:

mRealm = Realm.getDefaultInstance();

And then I use this region instance in the service:

mRealm.executeTransaction(realm -> {
        DocumentFileRealm documentFileRealm = realm.where(DocumentFileRealm.class)
                .equalTo("id", documentFileId)
                .findFirst();
        documentFileRealm.setDriveId(driveId);
    });

But when executing this last application throws an IllegalStateException. I do not know why. I'm not sure if this is due to the way I declared the service in my Android manifest, so I leave it here:

<service android:name=".package.UploadCompletionService" android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.drive.events.HANDLE_EVENT"/>
    </intent-filter>
</service>

Can I call Realm from a background service? What is wrong with the way I use it?

Thanks in advance.

+4
2

IntentService onHandleIntent doInBackground AsyncTask.

, , , Realm finally.

public class PollingService extends IntentService {
    @Override
    public void onHandleIntent(Intent intent) {
        Realm realm = null;
        try {
            realm = Realm.getDefaultInstance();
            // go do some network calls/etc and get some data 
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                     realm.createAllFromJson(Customer.class, customerApi.getCustomers()); // Save a bunch of new Customer objects
                }
            });
        } finally {
            if(realm != null) {
                realm.close();
            }
        }
    }
    // ...
}

onCreate , Realm , .

+1
public class MyThread extends Thread {
private Realm realm;
@Override
public void run() {
    Looper.prepare();
    realm = Realm.getDefaultInstance();
    try {
        //... Setup the handlers using the Realm instance ...
        Looper.loop();
    } finally {
        realm.close();
    }
}

}

-1

Source: https://habr.com/ru/post/1652895/


All Articles