当应用程序处于后台和前台时,我使用 aWorkManger
定期从我的数据库中检索信息。Firestore
此信息用于根据状态更新 UI(因此不同的状态会添加或删除 UI 的不同部分)。在第一次运行时效果很好,但是,一旦应用程序在后台并WorkManager
尝试运行,它就会崩溃并出现以下错误:
Caused by: java.lang.RuntimeException: Failed to gain exclusive lock to the Firestore client's offline persistence. This generally means you are using Firestore from multiple processes in your app. Keep in mind that multi-process Android apps execute the code in your Application class in all processes, so you may need to avoid initializing Firestore in your Application class. If you are intentionally using Firestore from multiple processes, you can only enable offline persistence (i.e. call setPersistenceEnabled(true)) in one of them.
最初我是这样做的:FirebaseFirestore firestore = FirebaseFirestore.getInstance();
在所有活动和片段中,因为错误表明在应用程序类中初始化是一个坏主意。但是,我仍然收到错误,我什至尝试在应用程序类中创建一个初始化实例,如下所示:
public FirebaseFirestore getFirestore(){
if(firestore == null){
firestore = FirebaseFirestore.getInstance();
}
return firestore;
}
WorkManager
但是每当运行时我仍然会看到这个错误。我已经尝试了这个问题的解决方案,因为它有点相似,但它没有解决错误。我还在某个地方看到不能在单独的线程上调用 firestore,否则我可能弄错了。
我相当确定这与我如何初始化和访问 firestore 实例有关,但我不确定如何修复它。我尝试在使用它的每个活动、片段和服务中使用单独的初始化,但没有运气。
编辑
工人阶级:
public class PopulateThemeCache extends Worker {
@Inject
FirebaseMethods mFirebaseMethods;
private ThemeDao themeDao;
private String themeKey;
public PopulateThemeCache() {
FireApp.getApp().getApplicationComponent().inject(this);
themeDao = PictematicOfflineCache.getDatabase(getApplicationContext()).themeDao();
}
@Override
@NonNull
public Result doWork() {
try{
Query query = FireApp.getApp().getFirestore().collection("themes").orderBy("start_time");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
//executed code here
}
});
Overall overall = new Overall();
query = FireApp.getApp().getFirestore().collection("profile_posts");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
//executed code
}
});
return Result.SUCCESS;
}catch (Throwable throwable){
Log.e("PopulateThemeCache", "Error caching", throwable);
return Result.FAILURE;
}
}}
MainActivity onCreate:
PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(PopulateThemeCache.class, 2, TimeUnit.HOURS)
.addTag("Theme_Update")
.build();
WorkManager.getInstance().enqueue(request);
我使用 Android Studio Assistant 工具集成了 firebase。上面的工人类查询一个theme
节点并检查当前可用的主题并更新房间数据库。