简体   繁体   English

用于Mediaplayer的Android AsyncTask通信

[英]Android AsyncTask communication for mediaplayer

My task is to download some files and play them sequentially. 我的任务是下载一些文件并按顺序播放。

Now I have an AsynkTask that call a server, wait until server produce file, and then download it, I do this for n files. 现在,我有一个AsynkTask来调用服务器,等到服务器生成文件,然后下载它,然后对n个文件执行此操作。 There is a final ArrayList in my Activity that is filled by AsyncTask with path of downloaded files. 我的活动中有一个最终的ArrayList,由AsyncTask填充并带有下载文件的路径。

Another Asynktask wait(using iteration with Thread.Sleep() and max number of iteration) in doInBackground that first element of ArrayList is filled, so it exit from doinbackground and in postexecute() initialize a VideoView with this file and play it, other files are played in OnCompletation method of VideoView. 在doInBackground中,另一个Asynktask等待(使用Thread.Sleep()进行迭代,并使用最大迭代次数)填充了ArrayList的第一个元素,因此它从doinbackground退出,并在postexecute()中使用此文件初始化VideoView并播放其他文件在VideoView的OnCompletation方法中播放。

Now I know that isn't best way to do this, and I'm searching for another way for communicate between Asynctask. 现在,我知道这不是最好的方法,我正在寻找另一种在Asynctask之间进行通信的方法。 I know that using global ArrayList and Thread.Sleep() in a While iteration isn't good. 我知道在While迭代中使用全局ArrayList和Thread.Sleep()不好。 I try using custom callback function, but code of function require UIThread because need to starts VideoView. 我尝试使用自定义回调函数,但是该函数的代码需要UIThread,因为需要启动VideoView。 So I can't call callback from doinBackground(). 所以我不能从doinBackground()调用回调。

Any suggestions ? 有什么建议么 ?

I don't think if asynctask is the best option for your situation. 我不认为asynctask是否是适合您情况的最佳选择。 One of the shortcomings is that you can't really wait in a asynctask for a callback of any sort (unless doing a dirty hack). 缺点之一是您不能真正地在asynctask中等待任何形式的回调(除非进行肮脏的hack)。

The other shortcoming is that by default asynctasks are running in serial, so you can't have one asynctask waiting for the result of another asynctask (this behavior can be changed, but I don't think if this is something you want to do). 另一个缺点是默认情况下asynctasks是串行运行的,所以您不能让一个asynctask等待另一个asynctask的结果(此行为可以更改,但是我不认为这是您要执行的操作) 。

A cleaner solution would be using HandlerThread, and then send messages between them. 较干净的解决方案是使用HandlerThread,然后在它们之间发送消息。 These threads will process a given message, or run a Runnable, and then wait until they get their next message/Runnable. 这些线程将处理给定的消息或运行Runnable,然后等待,直到获得下一条消息/ Runnable。 So you can easily setup the communication between them. 因此,您可以轻松地设置它们之间的通信。

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

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