我使用Realm作爲ORM來管理Android應用程序中的數據庫,一切都正常。但是,當我捕獲推送通知,然後嘗試使用Realm保存通知數據時,會發生錯誤。 下面是錯誤:Android - 如何在FirebaseMessagingService類中使用Realm(非活動)
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
這是我的課,從FirebaseMessagingService延伸:
public class SMovilFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null)
{
saveDataNotification(remoteMessage.getData().get("resourceId"), remoteMessage.getNotification().getTitle());
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
}
private void showNotification(String title, String body) {
Intent intent = new Intent(this, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
private void saveDataNotification(String resourceId, String message){
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
Notifications notification = realm.createObject(Notifications.class, setUniqueId(realm));
notification.setMessage(message);
notification.set_state("1");
notification.set_linkResource(resourceId);
realm.commitTransaction();
}
}
這是我的init境界類,這個類的應用延伸, BaseApplication是我的應用程序的名稱:
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
這我的文件的位置到項目:
我需要使用領域來保存接收到的信息在我的數據庫,但出現在該非活動文件此錯誤。
希望你能幫助我。 此致敬禮。
您需要爲不同的線程獲取單獨的Realm實例。請參閱https://realm.io/docs/java/latest/#threading – beeender
堆棧跟蹤將會很不錯,同時還有代碼'setUniqueId()' – EpicPandaForce
另請參閱您訪問Realm的活動的代碼。 –