当应用程序处于后台和前台时,我正在使用WorkManger
定期从我的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
运行时,我仍然会看到此错误。我尝试了this question的解决方案,因为它有点相似,但无法解决错误。我还看到某个地方无法在单独的线程上调用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。上面的worker类查询theme
节点并检查当前可用的主题并更新会议室数据库。