@OnLifecycleEvent is deprecated, use DefaultLifecycleObserver instead

This commit is contained in:
Benoit Marty 2021-11-09 16:56:51 +01:00 committed by Benoit Marty
parent 9429b039de
commit 0a9845af30
8 changed files with 72 additions and 90 deletions

View file

@ -16,9 +16,8 @@
package org.matrix.android.sdk.internal.util package org.matrix.android.sdk.internal.util
import androidx.lifecycle.Lifecycle import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import org.matrix.android.sdk.internal.di.MatrixScope import org.matrix.android.sdk.internal.di.MatrixScope
import timber.log.Timber import timber.log.Timber
import javax.inject.Inject import javax.inject.Inject
@ -27,13 +26,12 @@ import javax.inject.Inject
* To be attached to ProcessLifecycleOwner lifecycle * To be attached to ProcessLifecycleOwner lifecycle
*/ */
@MatrixScope @MatrixScope
internal class BackgroundDetectionObserver @Inject constructor() : LifecycleObserver { internal class BackgroundDetectionObserver @Inject constructor() : DefaultLifecycleObserver {
var isInBackground: Boolean = true var isInBackground: Boolean = true
private set private set
private private val listeners = LinkedHashSet<Listener>()
val listeners = LinkedHashSet<Listener>()
fun register(listener: Listener) { fun register(listener: Listener) {
listeners.add(listener) listeners.add(listener)
@ -43,15 +41,13 @@ internal class BackgroundDetectionObserver @Inject constructor() : LifecycleObse
listeners.remove(listener) listeners.remove(listener)
} }
@OnLifecycleEvent(Lifecycle.Event.ON_START) override fun onStart(owner: LifecycleOwner) {
fun onMoveToForeground() {
Timber.v("App returning to foreground…") Timber.v("App returning to foreground…")
isInBackground = false isInBackground = false
listeners.forEach { it.onMoveToForeground() } listeners.forEach { it.onMoveToForeground() }
} }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) override fun onStop(owner: LifecycleOwner) {
fun onMoveToBackground() {
Timber.v("App going to background…") Timber.v("App going to background…")
isInBackground = true isInBackground = true
listeners.forEach { it.onMoveToBackground() } listeners.forEach { it.onMoveToBackground() }

View file

@ -356,7 +356,10 @@ dependencies {
implementation libs.squareup.moshi implementation libs.squareup.moshi
kapt libs.squareup.moshiKotlin kapt libs.squareup.moshiKotlin
// Lifecycle
implementation libs.androidx.lifecycleLivedata implementation libs.androidx.lifecycleLivedata
implementation libs.androidx.lifecycleProcess
implementation libs.androidx.datastore implementation libs.androidx.datastore
implementation libs.androidx.datastorepreferences implementation libs.androidx.datastorepreferences

View file

@ -16,9 +16,8 @@
package im.vector.app package im.vector.app
import androidx.lifecycle.Lifecycle import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import arrow.core.Option import arrow.core.Option
import im.vector.app.core.di.ActiveSessionHolder import im.vector.app.core.di.ActiveSessionHolder
import im.vector.app.core.utils.BehaviorDataSource import im.vector.app.core.utils.BehaviorDataSource
@ -57,7 +56,7 @@ class AppStateHandler @Inject constructor(
private val sessionDataSource: ActiveSessionDataSource, private val sessionDataSource: ActiveSessionDataSource,
private val uiStateRepository: UiStateRepository, private val uiStateRepository: UiStateRepository,
private val activeSessionHolder: ActiveSessionHolder private val activeSessionHolder: ActiveSessionHolder
) : LifecycleObserver { ) : DefaultLifecycleObserver {
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val selectedSpaceDataSource = BehaviorDataSource<Option<RoomGroupingMethod>>(Option.empty()) private val selectedSpaceDataSource = BehaviorDataSource<Option<RoomGroupingMethod>>(Option.empty())
@ -133,13 +132,11 @@ class AppStateHandler @Inject constructor(
return (selectedSpaceDataSource.currentValue?.orNull() as? RoomGroupingMethod.ByLegacyGroup)?.groupSummary?.groupId return (selectedSpaceDataSource.currentValue?.orNull() as? RoomGroupingMethod.ByLegacyGroup)?.groupSummary?.groupId
} }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) override fun onResume(owner: LifecycleOwner) {
fun entersForeground() {
observeActiveSession() observeActiveSession()
} }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) override fun onPause(owner: LifecycleOwner) {
fun entersBackground() {
coroutineScope.coroutineContext.cancelChildren() coroutineScope.coroutineContext.cancelChildren()
val session = activeSessionHolder.getSafeActiveSession() ?: return val session = activeSessionHolder.getSafeActiveSession() ?: return
when (val currentMethod = selectedSpaceDataSource.currentValue?.orNull() ?: RoomGroupingMethod.BySpace(null)) { when (val currentMethod = selectedSpaceDataSource.currentValue?.orNull() ?: RoomGroupingMethod.BySpace(null)) {

View file

@ -27,9 +27,8 @@ import android.os.HandlerThread
import android.os.StrictMode import android.os.StrictMode
import androidx.core.provider.FontRequest import androidx.core.provider.FontRequest
import androidx.core.provider.FontsContractCompat import androidx.core.provider.FontsContractCompat
import androidx.lifecycle.Lifecycle import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner import androidx.lifecycle.ProcessLifecycleOwner
import androidx.multidex.MultiDex import androidx.multidex.MultiDex
import com.airbnb.epoxy.EpoxyAsyncUtil import com.airbnb.epoxy.EpoxyAsyncUtil
@ -166,9 +165,8 @@ class VectorApplication :
ProcessLifecycleOwner.get().lifecycle.addObserver(startSyncOnFirstStart) ProcessLifecycleOwner.get().lifecycle.addObserver(startSyncOnFirstStart)
ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleObserver { ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) override fun onResume(owner: LifecycleOwner) {
fun entersForeground() {
Timber.i("App entered foreground") Timber.i("App entered foreground")
FcmHelper.onEnterForeground(appContext, activeSessionHolder) FcmHelper.onEnterForeground(appContext, activeSessionHolder)
activeSessionHolder.getSafeActiveSession()?.also { activeSessionHolder.getSafeActiveSession()?.also {
@ -176,8 +174,7 @@ class VectorApplication :
} }
} }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) override fun onPause(owner: LifecycleOwner) {
fun entersBackground() {
Timber.i("App entered background") // call persistInfo Timber.i("App entered background") // call persistInfo
notificationDrawerManager.persistInfo() notificationDrawerManager.persistInfo()
FcmHelper.onEnterBackground(appContext, vectorPreferences, activeSessionHolder) FcmHelper.onEnterBackground(appContext, vectorPreferences, activeSessionHolder)
@ -198,9 +195,8 @@ class VectorApplication :
EmojiManager.install(GoogleEmojiProvider()) EmojiManager.install(GoogleEmojiProvider())
} }
private val startSyncOnFirstStart = object : LifecycleObserver { private val startSyncOnFirstStart = object : DefaultLifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START) override fun onStart(owner: LifecycleOwner) {
fun onStart() {
Timber.i("App process started") Timber.i("App process started")
authenticationService.getLastAuthenticatedSession()?.startSyncing(appContext) authenticationService.getLastAuthenticatedSession()?.startSyncing(appContext)
ProcessLifecycleOwner.get().lifecycle.removeObserver(this) ProcessLifecycleOwner.get().lifecycle.removeObserver(this)

View file

@ -18,58 +18,56 @@ package im.vector.app.core.platform
import androidx.annotation.MainThread import androidx.annotation.MainThread
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
fun <T> LifecycleOwner.lifecycleAwareLazy(initializer: () -> T): Lazy<T> = LifecycleAwareLazy(this, initializer) fun <T> LifecycleOwner.lifecycleAwareLazy(initializer: () -> T): Lazy<T> = LifecycleAwareLazy(this, initializer)
private object UninitializedValue private object UninitializedValue
class LifecycleAwareLazy<out T>( class LifecycleAwareLazy<out T>(
private val owner: LifecycleOwner, private val owner: LifecycleOwner,
initializer: () -> T initializer: () -> T
) : Lazy<T>, LifecycleObserver { ) : Lazy<T>, DefaultLifecycleObserver {
private var initializer: (() -> T)? = initializer private var initializer: (() -> T)? = initializer
private var _value: Any? = UninitializedValue private var _value: Any? = UninitializedValue
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
override val value: T override val value: T
@MainThread @MainThread
get() { get() {
if (_value === UninitializedValue) { if (_value === UninitializedValue) {
_value = initializer!!() _value = initializer!!()
attachToLifecycle() attachToLifecycle()
} }
return _value as T return _value as T
}
override fun onDestroy(owner: LifecycleOwner) {
_value = UninitializedValue
detachFromLifecycle()
} }
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) private fun attachToLifecycle() {
fun resetValue() { if (getLifecycleOwner().lifecycle.currentState == Lifecycle.State.DESTROYED) {
_value = UninitializedValue throw IllegalStateException("Initialization failed because lifecycle has been destroyed!")
detachFromLifecycle() }
} getLifecycleOwner().lifecycle.addObserver(this)
private fun attachToLifecycle() {
if (getLifecycleOwner().lifecycle.currentState == Lifecycle.State.DESTROYED) {
throw IllegalStateException("Initialization failed because lifecycle has been destroyed!")
} }
getLifecycleOwner().lifecycle.addObserver(this)
}
private fun detachFromLifecycle() { private fun detachFromLifecycle() {
getLifecycleOwner().lifecycle.removeObserver(this) getLifecycleOwner().lifecycle.removeObserver(this)
} }
private fun getLifecycleOwner() = when (owner) { private fun getLifecycleOwner() = when (owner) {
is Fragment -> owner.viewLifecycleOwner is Fragment -> owner.viewLifecycleOwner
else -> owner else -> owner
} }
override fun isInitialized(): Boolean = _value !== UninitializedValue override fun isInitialized(): Boolean = _value !== UninitializedValue
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
} }

View file

@ -20,9 +20,8 @@ import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.IntentFilter import android.content.IntentFilter
import androidx.lifecycle.Lifecycle import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.facebook.react.bridge.JavaOnlyMap import com.facebook.react.bridge.JavaOnlyMap
import org.jitsi.meet.sdk.BroadcastEmitter import org.jitsi.meet.sdk.BroadcastEmitter
@ -42,7 +41,7 @@ sealed class ConferenceEvent(open val data: Map<String, Any>) {
} }
} }
class ConferenceEventEmitter(private val context: Context) { class ConferenceEventEmitter(private val context: Context) {
fun emitConferenceEnded() { fun emitConferenceEnded() {
val broadcastEventData = JavaOnlyMap.of(CONFERENCE_URL_DATA_KEY, JitsiMeet.getCurrentConference()) val broadcastEventData = JavaOnlyMap.of(CONFERENCE_URL_DATA_KEY, JitsiMeet.getCurrentConference())
@ -52,7 +51,7 @@ class ConferenceEventEmitter(private val context: Context) {
class ConferenceEventObserver(private val context: Context, class ConferenceEventObserver(private val context: Context,
private val onBroadcastEvent: (ConferenceEvent) -> Unit) : private val onBroadcastEvent: (ConferenceEvent) -> Unit) :
LifecycleObserver { DefaultLifecycleObserver {
// See https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-android-sdk#listening-for-broadcasted-events // See https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-android-sdk#listening-for-broadcasted-events
private val broadcastReceiver = object : BroadcastReceiver() { private val broadcastReceiver = object : BroadcastReceiver() {
@ -61,8 +60,7 @@ class ConferenceEventObserver(private val context: Context,
} }
} }
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) override fun onDestroy(owner: LifecycleOwner) {
fun unregisterForBroadcastMessages() {
try { try {
LocalBroadcastManager.getInstance(context).unregisterReceiver(broadcastReceiver) LocalBroadcastManager.getInstance(context).unregisterReceiver(broadcastReceiver)
} catch (throwable: Throwable) { } catch (throwable: Throwable) {
@ -70,8 +68,7 @@ class ConferenceEventObserver(private val context: Context,
} }
} }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) override fun onCreate(owner: LifecycleOwner) {
fun registerForBroadcastMessages() {
val intentFilter = IntentFilter() val intentFilter = IntentFilter()
for (type in BroadcastEvent.Type.values()) { for (type in BroadcastEvent.Type.values()) {
intentFilter.addAction(type.action) intentFilter.addAction(type.action)

View file

@ -17,9 +17,8 @@
package im.vector.app.features.call.webrtc package im.vector.app.features.call.webrtc
import android.content.Context import android.content.Context
import androidx.lifecycle.Lifecycle import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import im.vector.app.ActiveSessionDataSource import im.vector.app.ActiveSessionDataSource
import im.vector.app.BuildConfig import im.vector.app.BuildConfig
import im.vector.app.core.services.CallService import im.vector.app.core.services.CallService
@ -70,7 +69,8 @@ private val loggerTag = LoggerTag("WebRtcCallManager", LoggerTag.VOIP)
class WebRtcCallManager @Inject constructor( class WebRtcCallManager @Inject constructor(
private val context: Context, private val context: Context,
private val activeSessionDataSource: ActiveSessionDataSource private val activeSessionDataSource: ActiveSessionDataSource
) : CallListener, LifecycleObserver { ) : CallListener,
DefaultLifecycleObserver {
private val currentSession: Session? private val currentSession: Session?
get() = activeSessionDataSource.currentValue?.orNull() get() = activeSessionDataSource.currentValue?.orNull()
@ -133,13 +133,11 @@ class WebRtcCallManager @Inject constructor(
private var isInBackground: Boolean = true private var isInBackground: Boolean = true
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) override fun onResume(owner: LifecycleOwner) {
fun entersForeground() {
isInBackground = false isInBackground = false
} }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) override fun onPause(owner: LifecycleOwner) {
fun entersBackground() {
isInBackground = true isInBackground = true
} }

View file

@ -17,11 +17,10 @@
package im.vector.app.features.pin package im.vector.app.features.pin
import android.os.SystemClock import android.os.SystemClock
import androidx.lifecycle.Lifecycle import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import im.vector.app.features.settings.VectorPreferences import im.vector.app.features.settings.VectorPreferences
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@ -41,7 +40,7 @@ private const val PERIOD_OF_GRACE_IN_MS = 2 * 60 * 1000L
class PinLocker @Inject constructor( class PinLocker @Inject constructor(
private val pinCodeStore: PinCodeStore, private val pinCodeStore: PinCodeStore,
private val vectorPreferences: VectorPreferences private val vectorPreferences: VectorPreferences
) : LifecycleObserver { ) : DefaultLifecycleObserver {
enum class State { enum class State {
// App is locked, can be unlock // App is locked, can be unlock
@ -87,16 +86,14 @@ class PinLocker @Inject constructor(
computeState() computeState()
} }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) override fun onResume(owner: LifecycleOwner) {
fun entersForeground() {
val timeElapsedSinceBackground = SystemClock.elapsedRealtime() - entersBackgroundTs val timeElapsedSinceBackground = SystemClock.elapsedRealtime() - entersBackgroundTs
shouldBeLocked = shouldBeLocked || timeElapsedSinceBackground >= getGracePeriod() shouldBeLocked = shouldBeLocked || timeElapsedSinceBackground >= getGracePeriod()
Timber.v("App enters foreground after $timeElapsedSinceBackground ms spent in background shouldBeLocked: $shouldBeLocked") Timber.v("App enters foreground after $timeElapsedSinceBackground ms spent in background shouldBeLocked: $shouldBeLocked")
computeState() computeState()
} }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) override fun onPause(owner: LifecycleOwner) {
fun entersBackground() {
Timber.v("App enters background") Timber.v("App enters background")
entersBackgroundTs = SystemClock.elapsedRealtime() entersBackgroundTs = SystemClock.elapsedRealtime()
} }