Android Crashlytics 在 Android 上直接启动时将无法初始化。问题在于,Android 中支持上下文的默认存储是加密的,直到用户输入其凭据为止:
您会在日志中看到一堆信息,例如
07-17 16:47:18.083 1897-1982/XXX E/SharedPreferencesImpl:无法创建目录 共享首选项文件 /data/user/0/com.xxx.xxx/shared_prefs/com.crashlytics.sdk.android:answers:settings.xml
还可以通过使用
initializationCallback
注册
Fabric.Builder
进行验证
有没有办法通过 createDeviceProtectedStorageContext 存储配置 crashlytics 以使用共享首选项后端?
问题是,如果应用程序以这种方式启动,那么 crashlytics 将在应用程序的生命周期内不起作用。这可能会导致丢失大量崩溃报告。
基本上它会失败,因为像 Crashlytics 这样的库会调用
getBaseContext
,这会使 createDeviceProtectedStorageContext
无效。对于 Crashlytics,它还期望 getApplicationContext
返回 Application
。这是完整的解决方法。
实现以下类:(将其翻译成Java应该不会太难)
@SuppressLint("MissingSuperCall", "Registered")
@TargetApi(24)
class DeviceStorageApp(context: Context) : Application() {
init {
attachBaseContext(context.createDeviceProtectedStorageContext())
}
/**
* Thou shalt not get the REAL underlying application context which would no
* longer be operating under device protected storage.
*/
override fun getApplicationContext(): Context = this
/**
* Forwarding Application calls to make libraries like Firebase sessions work.
*/
override fun onCreate() = app.onCreate()
override fun onTerminate() = app.onTerminate()
override fun onConfigurationChanged(newConfig: Configuration) =
app.onConfigurationChanged(newConfig)
override fun onLowMemory() = app.onLowMemory()
override fun onTrimMemory(level: Int) = app.onTrimMemory(level)
override fun registerComponentCallbacks(callback: ComponentCallbacks?) =
app.registerComponentCallbacks(callback)
override fun unregisterComponentCallbacks(callback: ComponentCallbacks?) =
app.unregisterComponentCallbacks(callback)
override fun registerActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks?) =
app.registerActivityLifecycleCallbacks(callback)
override fun unregisterActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks?) =
app.unregisterActivityLifecycleCallbacks(callback)
override fun registerOnProvideAssistDataListener(callback: OnProvideAssistDataListener?) =
app.registerOnProvideAssistDataListener(callback)
override fun unregisterOnProvideAssistDataListener(callback: OnProvideAssistDataListener?) =
app.unregisterOnProvideAssistDataListener(callback)
}
通过删除相应的提供程序来禁用自动初始化:
<provider android:name="com.google.firebase.provider.FirebaseInitProvider"
tools:node="remove"/>
然后在你的真实
Application.onCreate
中,执行以下操作:(Android SDK版本检查省略)
FirebaseApp.initializeApp(DeviceStorageApp(this))
编辑:添加了转发呼叫以使 Firebase 会话正常工作。