【发布时间】:2017-04-11 07:24:32
【问题描述】:
我使用 Realm 作为 ORM 来管理 Android 应用程序中的数据库,一切正常。但是,当我收到推送通知,然后尝试使用 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();
}
}
这是我初始化 Realm 的类,这个类从 Application 扩展而来,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 将接收到的信息保存在我的数据库中,但是这个非活动文件中出现了这个错误。
希望你能帮助我。 问候。
【问题讨论】:
-
你需要为不同的线程获取一个单独的Realm实例。见realm.io/docs/java/latest/#threading
-
一个堆栈跟踪会很好,还有
setUniqueId()的代码 -
请从您访问 Realm 的活动中获取代码。
-
我们需要堆栈跟踪和来自
setUniqueId的代码才能提供帮助。
标签: android firebase notifications realm firebase-cloud-messaging