Android的UI线程消息队列调度命令队列、线程、命令、消息

2023-09-14 00:07:28 作者:我是流氓我怕谁

虽然有保留的Andr​​oid碎片举行期间配置的变化,我想这是最好的办法是AsyncTask的工作,有些疑惑的出现在我的脑海里约的UI消息队列调用顺序。

While working with retain Fragments in Android to hold an AsyncTask during configuration changes, which i guess it's the best approach, some doubts appear in my mind about UI Message Queue invocation order.

例如: 想象一下这样的场景:

Ex: Imagine this scenario:

在配置发生变化时,用户旋转设备。 AsyncTask的运行。 片段 onDetach()叫 的AsyncTask doInBackground()方法完成 的AsyncTask onPostExecute()叫 片段 onAttach()叫 Configuration Change occurs, user rotates the device. AsyncTask is running. Fragment onDetach() is called AsyncTask doInBackground() method finishes AsyncTask onPostExecute()is called Fragment onAttach() is called

这样可以UI线程消息队列是这样的:

So can UI Thread Message Queue be like this:

队列前 - > onDetach()| onPostExecute()| onAttach()

Queue top -> onDetach() | onPostExecute() | onAttach()

我知道这不可能,调用 onPostExecute()将等待配置更改完成,据我所知,但如何运作的?从活动的呼吁,片段生命周期执行的连续?

I know it cannot, the call to onPostExecute() will wait until the configuration change completes, as far as i know, but how does that work ? Are the calls from Activities, Fragments life-cycles executed consecutively ?

推荐答案

这是不可能的 onPostExecute()被称为片段#onDetach()配置变更过程中和片段#onAttach()。这种说法背后的原因有三个方面:

It is not possible for onPostExecute() to be called in between Fragment#onDetach() and Fragment#onAttach() during a configuration change. The reasoning behind this claim is threefold:

配置更改在主线程的消息队列一条消息内处理。

Configuration changes are handled inside a single message in the main thread's message queue.

只要 doInBackground()方法返回时,的AsyncTask 日程表 onPostExecute()将通过发布消息到主线程的消息队列在主线程中调用的方法。

As soon as the doInBackground() method returns, the AsyncTask schedules the onPostExecute() method to be invoked on the main thread by posting a message to the main thread's message queue.

配置更改的消息将包含code将调用活动片段生命周期方法(如 onDetach() onAttach())。该的AsyncTask 的消息将包含code将调用 onPostExecute()方法。由于主线程在它的消息队列顺序处理的消息,这是不可能的两个消息的同时被执行,并且因此 onPostExecute()永远不能在调用在调用 onDetach() onAttach()

The configuration change's message will contain the code that will invoke the Activity and Fragment lifecycle methods (such as onDetach() and onAttach()). The AsyncTask's message will contain the code that will invoke the onPostExecute() method. Since the main thread processes messages in its message queue sequentially, it is impossible for the two messages to be executed at the same time, and therefore onPostExecute() can never be invoked in between the calls to onDetach() and onAttach().

阅读我在这个线程更详细的解释,回应道格·史蒂文森(包括链接到源$ C ​​$ C能够证明索赔)。

Read my response to Doug Stevenson in this thread for a more detailed explanation (including links to the source code that prove the claim).