花了3个小时搜索解决方案,但却没有。
我使用Firebase数据库,每当我从activity / fragment中使用它时,一切正常,但每当我尝试在后台服务中使用它时,即使我在使用之前启动它(并且首先使用setPersistent enable),它也会崩溃应用程序。
错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: dreamchasers.com.coinpal, PID: 8565
com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
at com.google.firebase.database.FirebaseDatabase.zziF(Unknown Source)
at com.google.firebase.database.FirebaseDatabase.setPersistenceEnabled(Unknown Source)
at dreamchasers.com.coinpal.services.FirebaseBackgroundService.getDatabase32(FirebaseBackgroundService.java:297)
at dreamchasers.com.coinpal.services.FirebaseBackgroundService.queryAlerts(FirebaseBackgroundService.java:85)
at dreamchasers.com.coinpal.services.FirebaseBackgroundService.onStartJob(FirebaseBackgroundService.java:70)
at com.firebase.jobdispatcher.JobService.start(JobService.java:127)
at com.firebase.jobdispatcher.JobServiceConnection.onServiceConnected(JobServiceConnection.java:65)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1516)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1544)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
我的后台服务firebase引用init方法:
public static DatabaseReference getDatabase32() {
if (mDatabase == null) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
return mDatabase;
}
请提供帮助,欢迎任何帮助,提前致谢!
答案 0 :(得分:1)
那么, 每次我使用setPersistenceEnabled时,我都是通过app.java
来做的只需创建类似的类:
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
所有你需要的工作,都放在AndroidManifest.xml属性中的application
标签android:name =“。App”。
<!-- other xml stuff -->
<application ... android:name=".App">
<!-- yet another stuff like nextline -->
<activity ... />
</application>