简体   繁体   English

AsyncTask中的Android AsyncTask

[英]Android AsyncTask inside AsyncTask

So, I'm working on a barcode decoder, which once we have the barcode goes to multiples API over the internet to decode what was just scanned. 所以,我正在研究一种条形码解码器,一旦我们将条形码转换为互联网上的倍数API,就可以解码刚刚扫描过的内容。 The thing is that I have to link some XML parsing together, and I don't know if I'm doing it right. 问题是我必须将一些XML解析链接在一起,我不知道我是否做得对。

So, once the barcode is scanned, my program calls an ASyncTask which goes over an API to retrieve the product name. 因此,一旦条形码被扫描,我的程序就会调用一个ASyncTask,它通过一个API来检索产品名称。 Once it has the name, I want it to call another ASyncTask. 一旦有了名称,我希望它能够调用另一个ASyncTask。 I know this is possible by instantiating an ASyncTaks in the onPostExecute() of the other but, I think this is wrong, because it's like boxes within boxes. 我知道这可以通过在另一个的onPostExecute()中实例化ASyncTaks来实现,但我认为这是错误的,因为它就像盒子里的盒子一样。 So isn't it possible/better to instantiate my second ASyncTask inside my main Activity, and make it wait until my first ASyncTask is finished ? 那么在我的主Activity中实例化我的第二个ASyncTask是不是可能/更好,并让它等到我的第一个ASyncTask完成之后?

(english isn't my primary language, I hope I made myself clear). (英语不是我的主要语言,我希望我能说清楚)。

I think it's absolutely legitimate to start the second AsyncTask in the onPostExecute of the first AsyncTask, Mixing both operations is a bad logical idea, As "The Offspring" said - "You've gotta keep 'em separated" 我认为在第一个AsyncTask的onPostExecute中启动第二个AsyncTask是绝对合法的,混合这两个操作是一个不合逻辑的想法,因为“后代”说 - “你必须让他们分开”

If you don't want it to be directly inside the onPostExecute itself, set a handler to execute it in the activity and call this handler from onPostExecute . 如果您不希望它直接位于onPostExecute本身内,请设置一个处理程序以在活动中执行它,并从onPostExecute调用此处理程序。

And last thing - If you have a lot of logic - move it to a separate file, don't keep it all at the same file. 最后一件事 - 如果你有很多逻辑 - 将它移动到一个单独的文件,不要把它全部保存在同一个文件中。

In situations like this it might be better to batch long running operations together in one AsyncTask. 在这种情况下,最好在一个AsyncTask中将长时间运行的操作批处理。

Another option is to use the Loaders API, this makes chaining tasks much easier http://developer.android.com/guide/topics/fundamentals/loaders.html 另一种选择是使用Loaders API,这使得链接任务变得更加容易http://developer.android.com/guide/topics/fundamentals/loaders.html

You can go for another approach if you are facing often a situation like this. 如果你经常遇到这样的情况,你可以采取另一种方法。 That is to merge requests and operations inside of runnables/callables and to manage them separately within say a queue for instance. 那就是在runnables / callables中合并请求和操作,并在例如队列中单独管理它们。 Here is a nice approach. 这是一个很好的方法。 http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/ http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM