Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: changes to try to improve app startup and ANRs [WPB-6048] #2597

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ dependencies {
implementation(libs.androidx.splashscreen)
implementation(libs.androidx.exifInterface)
implementation(libs.androidx.biometric)
implementation(libs.androidx.startup)

implementation(libs.ktx.dateTime)
implementation(libs.material)
Expand Down
2 changes: 1 addition & 1 deletion app/src/dev/kotlin/com/wire/android/util/DataDogLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ object DataDogLogger : LogWriter() {

private val logger = Logger.Builder()
.setNetworkInfoEnabled(true)
.setLogcatLogsEnabled(true)
.setLogcatLogsEnabled(false) // we already use platformLogWriter() along with DataDogLogger, don't need duplicates in LogCat
.setDatadogLogsEnabled(true)
.setBundleWithTraceEnabled(true)
.setLoggerName("DATADOG")
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ object DataDogLogger : LogWriter() {

private val logger = Logger.Builder()
.setNetworkInfoEnabled(true)
.setLogcatLogsEnabled(true)
.setLogcatLogsEnabled(false) // we already use platformLogWriter() along with DataDogLogger, don't need duplicates in LogCat
.setDatadogLogsEnabled(true)
.setBundleWithTraceEnabled(true)
.setLoggerName("DATADOG")
.build()
Expand Down
39 changes: 17 additions & 22 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -199,17 +199,34 @@
</intent-filter>
</activity>

<!--
We make a custom Firebase init, because the app selects the Firebase project at a runtime,
so we need to remove default FirebaseInitProvider and create our custom FirebaseInitializer.
-->
<provider
android:name="com.google.firebase.provider.FirebaseInitProvider"
android:authorities="${applicationId}.firebaseinitprovider"
tools:node="remove" />

<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">

<!--
We create custom WorkManager Configuration.Provider and initialize on-demand,
so we need to remove default WorkManagerInitializer.
-->
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />

<meta-data
android:name="com.wire.android.initializer.FirebaseInitializer"
android:value="androidx.startup" />

</provider>

<provider
Expand Down Expand Up @@ -271,28 +288,6 @@
android:exported="false"
android:foregroundServiceType="phoneCall" />

<!-- If you want to disable android.startup completely. -->
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
tools:node="remove" />

<provider
android:name="com.google.firebase.provider.FirebaseInitProvider"
android:authorities="${applicationId}.firebaseinitprovider"
tools:node="remove" />
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<!-- If you are using androidx.startup to initialize other components -->
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>

</application>

</manifest>
69 changes: 31 additions & 38 deletions app/src/main/kotlin/com/wire/android/WireApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,11 @@ import android.os.Build
import android.os.StrictMode
import androidx.work.Configuration
import co.touchlab.kermit.platformLogWriter
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.wire.android.datastore.GlobalDataStore
import com.wire.android.di.ApplicationScope
import com.wire.android.di.KaliumCoreLogic
import com.wire.android.util.DataDogLogger
import com.wire.android.util.LogFileWriter
import com.wire.android.util.extension.isGoogleServicesAvailable
import com.wire.android.util.getGitBuildId
import com.wire.android.util.lifecycle.ConnectionPolicyManager
import com.wire.android.workmanager.WireWorkerFactory
Expand Down Expand Up @@ -83,23 +80,19 @@ class WireApplication : Application(), Configuration.Provider {

enableStrictMode()

if (this.isGoogleServicesAvailable()) {
val firebaseOptions = FirebaseOptions.Builder()
.setApplicationId(BuildConfig.FIREBASE_APP_ID)
.setGcmSenderId(BuildConfig.FIREBASE_PUSH_SENDER_ID)
.setApiKey(BuildConfig.GOOGLE_API_KEY)
.setProjectId(BuildConfig.FCM_PROJECT_ID)
.build()
FirebaseApp.initializeApp(this, firebaseOptions)
}
globalAppScope.launch {
initializeApplicationLoggingFrameworks()

initializeApplicationLoggingFrameworks()
connectionPolicyManager.startObservingAppLifecycle()
appLogger.i("$TAG app lifecycle")
connectionPolicyManager.startObservingAppLifecycle()

// TODO: Can be handled in one of Sync steps
coreLogic.updateApiVersionsScheduler.schedulePeriodicApiVersionUpdate()
appLogger.i("$TAG api version update")
// TODO: Can be handled in one of Sync steps
coreLogic.updateApiVersionsScheduler.schedulePeriodicApiVersionUpdate()

globalObserversManager.observe()
appLogger.i("$TAG global observers")
globalObserversManager.observe()
}
}

private fun enableStrictMode() {
Expand All @@ -123,29 +116,27 @@ class WireApplication : Application(), Configuration.Provider {
}
}

private fun initializeApplicationLoggingFrameworks() {
globalAppScope.launch {
// 1. Datadog should be initialized first
ExternalLoggerManager.initDatadogLogger(applicationContext, globalDataStore)
// 2. Initialize our internal logging framework
val isLoggingEnabled = globalDataStore.isLoggingEnabled().first()
val config = if (isLoggingEnabled) {
KaliumLogger.Config.DEFAULT.apply {
setLogLevel(KaliumLogLevel.VERBOSE)
setLogWriterList(listOf(DataDogLogger, platformLogWriter()))
}
} else {
KaliumLogger.Config.disabled()
private suspend fun initializeApplicationLoggingFrameworks() {
// 1. Datadog should be initialized first
ExternalLoggerManager.initDatadogLogger(applicationContext, globalDataStore)
// 2. Initialize our internal logging framework
val isLoggingEnabled = globalDataStore.isLoggingEnabled().first()
val config = if (isLoggingEnabled) {
KaliumLogger.Config.DEFAULT.apply {
setLogLevel(KaliumLogLevel.VERBOSE)
setLogWriterList(listOf(DataDogLogger, platformLogWriter()))
}
// 2. Initialize our internal logging framework
AppLogger.init(config)
CoreLogger.init(config)
// 3. Initialize our internal FILE logging framework
logFileWriter.start()
// 4. Everything ready, now we can log device info
appLogger.i("Logger enabled")
logDeviceInformation()
} else {
KaliumLogger.Config.disabled()
}
// 2. Initialize our internal logging framework
AppLogger.init(config)
CoreLogger.init(config)
// 3. Initialize our internal FILE logging framework
logFileWriter.start()
// 4. Everything ready, now we can log device info
appLogger.i("Logger enabled")
logDeviceInformation()
}

private fun logDeviceInformation() {
Expand Down Expand Up @@ -192,5 +183,7 @@ class WireApplication : Application(), Configuration.Provider {
values().firstOrNull { it.level == value } ?: TRIM_MEMORY_UNKNOWN
}
}

private const val TAG = "WireApplication"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Wire
* Copyright (C) 2024 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.wire.android.initializer

import android.content.Context
import androidx.startup.Initializer
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.wire.android.BuildConfig
import com.wire.android.util.extension.isGoogleServicesAvailable

class FirebaseInitializer : Initializer<Unit> {
override fun create(context: Context) {
if (context.isGoogleServicesAvailable()) {
val firebaseOptions = FirebaseOptions.Builder()
.setApplicationId(BuildConfig.FIREBASE_APP_ID)
.setGcmSenderId(BuildConfig.FIREBASE_PUSH_SENDER_ID)
.setApiKey(BuildConfig.GOOGLE_API_KEY)
.setProjectId(BuildConfig.FCM_PROJECT_ID)
.build()
FirebaseApp.initializeApp(context, firebaseOptions)
}
}
override fun dependencies(): List<Class<out Initializer<*>>> = emptyList() // no dependencies on other libraries
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Wire
* Copyright (C) 2024 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.wire.android.initializer

import android.content.Context
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent

@EntryPoint
@InstallIn(SingletonComponent::class)
interface InitializerEntryPoint {

companion object {
// a helper method to resolve the InitializerEntryPoint from the context
fun resolve(context: Context): InitializerEntryPoint {
val appContext = context.applicationContext ?: throw IllegalStateException()
return EntryPointAccessors.fromApplication(appContext, InitializerEntryPoint::class.java)
}
}
}
45 changes: 30 additions & 15 deletions app/src/main/kotlin/com/wire/android/ui/WireActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import com.wire.android.util.debug.FeatureVisibilityFlags
import com.wire.android.util.debug.LocalFeatureVisibilityFlags
import com.wire.android.util.deeplink.DeepLinkResult
import com.wire.android.util.ui.updateScreenSettings
import dagger.Lazy
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collectLatest
Expand All @@ -110,7 +111,7 @@ class WireActivity : AppCompatActivity() {
lateinit var proximitySensorManager: ProximitySensorManager

@Inject
lateinit var lockCodeTimeManager: LockCodeTimeManager
lateinit var lockCodeTimeManager: Lazy<LockCodeTimeManager>

private val viewModel: WireActivityViewModel by viewModels()

Expand All @@ -124,26 +125,39 @@ class WireActivity : AppCompatActivity() {
private var shouldKeepSplashOpen = true

override fun onCreate(savedInstanceState: Bundle?) {

appLogger.i("$TAG splash install")
// We need to keep the splash screen open until the first screen is drawn.
// Otherwise a white screen is displayed.
// It's an API limitation, at some point we may need to remove it
installSplashScreen().setKeepOnScreenCondition {
shouldKeepSplashOpen
}
val splashScreen = installSplashScreen()
super.onCreate(savedInstanceState)
proximitySensorManager.initialize()
splashScreen.setKeepOnScreenCondition { shouldKeepSplashOpen }

lifecycle.addObserver(currentScreenManager)
WindowCompat.setDecorFitsSystemWindows(window, false)

viewModel.observePersistentConnectionStatus()
val startDestination = when (viewModel.initialAppState) {
InitialAppState.NOT_MIGRATED -> MigrationScreenDestination
InitialAppState.NOT_LOGGED_IN -> WelcomeScreenDestination
InitialAppState.LOGGED_IN -> HomeScreenDestination
}
setComposableContent(startDestination) {
shouldKeepSplashOpen = false
handleDeepLink(intent, savedInstanceState)
appLogger.i("$TAG proximity sensor")
proximitySensorManager.initialize() // needs to be executed sequentially in blocking manner

lifecycleScope.launch {

appLogger.i("$TAG persistent connection status")
viewModel.observePersistentConnectionStatus()

appLogger.i("$TAG start destination")
val startDestination = when (viewModel.initialAppState) {
InitialAppState.NOT_MIGRATED -> MigrationScreenDestination
InitialAppState.NOT_LOGGED_IN -> WelcomeScreenDestination
InitialAppState.LOGGED_IN -> HomeScreenDestination
}

appLogger.i("$TAG composable content")
setComposableContent(startDestination) {
appLogger.i("$TAG splash hide")
shouldKeepSplashOpen = false
handleDeepLink(intent, savedInstanceState)
}
}
}

Expand Down Expand Up @@ -375,7 +389,7 @@ class WireActivity : AppCompatActivity() {
super.onResume()

lifecycleScope.launch {
lockCodeTimeManager.observeAppLock()
lockCodeTimeManager.get().observeAppLock()
// Listen to one flow in a lifecycle-aware manner using flowWithLifecycle
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.first().let {
Expand Down Expand Up @@ -469,6 +483,7 @@ class WireActivity : AppCompatActivity() {

companion object {
private const val HANDLED_DEEPLINK_FLAG = "deeplink_handled_flag_key"
private const val TAG = "WireActivity"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import com.wire.android.di.KaliumCoreLogic
import com.wire.kalium.logic.CoreLogic
import com.wire.kalium.logic.feature.session.CurrentSessionResult
import com.wire.kalium.logic.feature.session.CurrentSessionUseCase
import dagger.Lazy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.inject.Inject
Expand All @@ -41,8 +42,8 @@ import javax.inject.Singleton
@Singleton
class ProximitySensorManager @Inject constructor(
private val context: Context,
private val currentSession: CurrentSessionUseCase,
@KaliumCoreLogic private val coreLogic: CoreLogic,
private val currentSession: Lazy<CurrentSessionUseCase>,
@KaliumCoreLogic private val coreLogic: Lazy<CoreLogic>,
@ApplicationScope private val appCoroutineScope: CoroutineScope
) {

Expand Down Expand Up @@ -71,11 +72,11 @@ class ProximitySensorManager @Inject constructor(

override fun onSensorChanged(event: SensorEvent) {
appCoroutineScope.launch {
coreLogic.globalScope {
when (val currentSession = currentSession()) {
coreLogic.get().globalScope {
when (val currentSession = currentSession.get().invoke()) {
is CurrentSessionResult.Success -> {
val userId = currentSession.accountInfo.userId
val isCallRunning = coreLogic.getSessionScope(userId).calls.isCallRunning()
val isCallRunning = coreLogic.get().getSessionScope(userId).calls.isCallRunning()
val distance = event.values.first()
val shouldTurnOffScreen = distance == NEAR_DISTANCE && isCallRunning
appLogger.i(
Expand Down
Loading
Loading