2016-08-29 6 views
4

私はAndroidアプリケーションでRealmを使用しています。CompletionEvent経由でGoogleドライブから通知を受けていますので、サービス内のレルムデータベースを変更する必要があります。Androidバックグラウンドサービスのレルム

私が手に例外がある:

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

そして、私のサービスからのonCreateで、私は自分のレルムを取得しています:私は私のApplicationクラスに次の方法を私のデフォルト構成を設定している

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

mRealm = Realm.getDefaultInstance(); 

次に、サービスでこのレルムインスタンスを使用します。

しかし、この最後のアプリケーションを実行すると、アプリはIllegalStateExceptionを起動します。どうしてか分かりません。私はそれが私がここにそれを残すように、私はアンドロイドのマニフェストでサービスを宣言した方法とは何かを持っているかどうかわからないです:

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

は、バックグラウンドサービスからレルムを呼び出すことが可能ですか?私がこれを使用している方法で何が間違っていますか?

ありがとうございます。

+2

この 'mRealm = Realm.getDefaultInstance();をonHandleIntentに移動してみてください –

+0

これは機能します!ありがとうございました。 –

答えて

1

IntentServiceでは、onHandleIntentメソッドを、AsyncTaskのdoInBackgroundメソッドのように扱うことになっています。

したがって、バックグラウンドスレッドで実行され、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 UIスレッド上で動作し、そのレルムのあなたの初期化には、外出先ではない別のスレッド上で発生します。

+0

IntentServiceではなくサービスですが、とにかく同じ方法で動作し、onCreateメソッドがUIスレッドで実行されています。ありがとうございます。 –

+0

例外をスローする---現在のスレッドで非同期クエリを作成できません。レルムはIntentServiceスレッドで自動的に更新できません –

+0

@ Dr.aNdRO私のコードには非同期APIのものが含まれていないことがほぼ120%であるため、エラーはあなたのコードと私のコードが異なるところにあります。 – EpicPandaForce

関連する問題