我使用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的活动的代码。 –