adroid studio 中的“卡顿”警报有多准确?

问题描述 投票:0回答:1

我有一个简单的应用程序,它在 MainViewModel java 类中的单独线程中执行一些不太复杂的计算,其方法是从 MainActivity.java 类中调用的,该类依次更新一个带有两个按钮、两个文本字段的非常简单的 UI和文本视图。 我收到这些高跳帧警告:

2024-04-28 15:32:20.893 20041-20041/com.niff.inout I/Choreographer: Skipped 365 frames!  The application may be doing too much work on its main thread.
2024-04-28 15:32:31.805 20041-20041/com.niff.inout I/Choreographer: Skipped 298 frames!  The application may be doing too much work on its main thread.
2024-04-28 15:33:25.564 20041-20041/com.niff.inout I/Choreographer: Skipped 2733 frames!  The application may be doing too much work on its main thread.

我大部分时间都使用模拟器(API 级别 30),但我的设备上也出现了警告 - 有一次跳过了 16,000 帧以上。 它们似乎是在应用程序加载到模拟器或设备时出现的。我已经重写了 MainActivity 的“onResume()”方法,以从文件中读取非常简单的数据(同样,在 MainViewModel.java 中的单独线程上)。 警告是随机且不一致的 - 我可以连续几天看到跳帧数低于 50,然后突然间跳帧数达到数千。但我从未注意到模拟器或设备上的屏幕有任何闪烁,我认为这是“卡顿”的主要症状。 我在调试版本和发布版本上都收到了警告,事实上 16,000 的警告是(我认为)在我设备上的发布版本上。 我不知道这有多相关,但是当我在调试版本和发布版本之间切换时,我收到“IDE 错误”(Android Studio Chipmunk)。 我尝试遵循此处的建议https://developer.android.com/studio/profile/jank-detection但并不真正理解分析器的使用说明。 我的笔记本电脑上只有 8Mb RAM - 这是一个因素吗? 忘记代码中的调试断点会影响此问题吗?

android jank
1个回答
0
投票

较新的设备可能不会遇到问题,但较旧的设备肯定会注意到。

最好的办法是将尽可能多的工作抽象到协程中,以便它异步运行。

https://kotlinlang.org/docs/coroutines-overview.html

然后在数据可用时使用 LiveData 通知 UI。 https://developer.android.com/topic/libraries/architecture/livedata

这是使用 ViewModel 实现 LiveData/Flow 的示例。 所以,假设您有一个简单的应用程序,可以将笔记写入房间存储。

这就是道

@Dao
interface NotesHandler{
    fun getNotes() : Flow<List<Notes>>
}

@HiltViewModel
class MyViewModel @Inject constructor (val myDbContext: RoomDatabase): ViewModel(){

     val notesHandler = myDbContext.getNotesHandler().getNotes().asLiveData()
}

然后在您的活动/片段中(onCreate):

    private val viewModel by viewModels<MyViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        viewModel.notesHandler.observe(this){
            // my data is process here
            binding.textView.text = it[0].note
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.