与 Jetpack compose 一起使用时,我遇到了 Timber 的问题。我试图记录响应设备轮换的语句。使用 Timber,每次循环都会比前一个生成多一条日志语句。因此,第一次轮换生成一个日志语句,第二次轮换生成两条日志语句,依此类推。这给人的印象是,要么操作系统多次通知我,要么 Jetpack compose 正在发挥其魔力。在追了我一整天的尾巴之后,我终于用原木取代了木材。结果是不再有重复的日志语句。这是一个已知问题,还是我做错了什么?这是对旋转做出反应的代码: 如果将 Log 替换为 Timber,则会多次打印 ########## ORIENTATION previousOrientation。
@Composable
fun OrientationListener(onPortrait: () -> Unit, onLandscape: () -> Unit) {
var previousOrientation by rememberSaveable { mutableIntStateOf(Configuration.ORIENTATION_UNDEFINED) }
val configuration = LocalConfiguration.current
// Use LaunchedEffect to detect orientation changes and call the appropriate callback
LaunchedEffect(configuration.orientation) {
if (previousOrientation != configuration.orientation) {
Log.d(TAG,"########## ORIENTATION previousOrientation: $previousOrientation current configuration: ${configuration.orientation}###############")
previousOrientation = configuration.orientation
val isPortrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
if (isPortrait) {
onPortrait()
} else {
onLandscape()
}
}
}
}
用 TImber 替换 Log 会导致多条日志语句打印到控制台。 Timber 在 MainActivity 中初始化,如下所示:
if (BuildConfig.DEBUG)
Timber.plant(Timber.DebugTree())
我发现当您在
Timber
类中而不是在 Application
中初始化 Activity
时,它会按预期工作。
请创建一个类
MyApplication.kt
并在其中添加以下代码:
class MyApplication: Application() {
override fun onCreate() {
super.onCreate()
// setup Timber
Timber.plant(Timber.DebugTree())
}
}
然后,在您的
Application
中注册您的自定义 manifest.xml
类,如下所示:
<application
android:name=".MyApplication"
...>
</application>
如果这解决了您案例中的问题,请报告。