这对我来说是最令人困惑的话题之一。所以我的问题是,完成后传达后台线程结果的正确方法是什么?.
想象一下,我想TextView用我刚刚下载的一些信息更新一些信息。当我需要执行后台任务时,我使用了 3 样东西:
非常容易使用,这个onPostExecute()方法有将结果直接返回给 UiThread的方法,这样我就可以使用回调接口或做任何我想做的事情。我喜欢这门课,但它已被弃用。
这就是我在需要执行后台任务时实际使用的方法,而我的问题就出现在我必须将结果提供给 UiThread 的那一刻。我自己了解Looper和Handler类以及有关mainLooper。
所以,当我需要返回一些结果时,我使用的方法runOnUiThread(),正如我所读到的,只是获取LooperUi 线程的 并将我Runnable的发布到队列中。
嗯,这是有效的,我可以与主线程通信,但是,我发现它真的很难看,而且我确信有一种比填充我所有的“ runOnUiThread()”方法代码更优雅的方法。此外,如果后台任务需要太多时间,也许用户已经更改Activity或Fragment当内部代码runOnUiThread()运行时会导致什么Exceptions(我知道使用LiveData和MVVM模式可以解决最后一个问题,但我在一个遗留项目中工作,我不能重构所有代码,以便我使用经典的 Activity mvc 模式)
那么,还有另一种方法吗?你能举个例子吗?我真的搜索了很多,但没有找到任何东西......
我实际上在一个遗留项目中工作,我必须使用 Java,所以不能使用 Kotlin coroutines,但我发现它们易于使用且功能强大。
任何帮助,将不胜感激!
java multithreading android android-asynctask threadpoolexecutor
In Java it's easy to know when you have to try - catch a piece of code because the compiler force you to do it and the method declaration have the throws keyword with the Exceptions that will be throw.
For example:
void testMethod() throws Exception {
throw new Exception("test");
}
Run Code Online (Sandbox Code Playgroud)
But in Kotlin would be something like:
fun testMethod() {
throw Exception("test")
}
Run Code Online (Sandbox Code Playgroud)
How can I know in Kotlin that a piece of code provided by a class need …