【发布时间】:2013-01-13 22:47:36
【问题描述】:
我一直在尝试从 url 下载视频,我已经在 asynctask 的 doInBackground() 中实现了我的下载方法,但是 doInBackground 方法需要很长时间才能被调用(5-10 分钟),我是使用另一个异步任务在我被指示下载视频活动的活动中下载图像并且它工作正常。我的 onPreExecute 方法正在按时调用,但之后 doInBackground 需要将近 5-7 分钟才能启动。我将非常感谢提供的任何帮助。 这是我的代码
btnDownloadLQ.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0)
{
try
{
new DownloadVideoTask().execute(videoURL);
}
catch(Exception e)
{
Log.e("Vidit_TAG","I got an error",e);
}
}
});
private class DownloadVideoTask extends AsyncTask<String, String, String>
{
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
protected String doInBackground(String... urls)
{
int i=0;
try
{
URL url = new URL (urls[0]);
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
String root = Environment.getExternalStorageDirectory().toString();
File storagePath = new File(root + "/vidit");
storagePath.mkdirs();
OutputStream output = new FileOutputStream (new File(storagePath,title+".mp4"));
try
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
{
output.write(buffer, 0, bytesRead);
}
}
catch(Exception e)
{
Log.e("Vidit_TAG","I got an error",e);
}
finally
{
output.close();
}
}
catch(Exception e)
{
Log.e("Vidit_TAG","I got an error",e);
}
finally
{
input.close();
//tvTitle.setText("Completed");
}
}
catch(Exception e)
{
Log.e("Vidit_TAG","I got an error",e);
}
return null;
}
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(String unused)
{
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
alertbox(title);
}
}
【问题讨论】:
-
你能发布你的代码吗?一旦 onPreExecute 完成(并且它存在),doInBackground 就会被调用,因此您调用它的方式或 onPreExecute 肯定有问题。
-
可能他正在使用延迟的帖子,10分钟后不可能运行
-
@D_Steve595 我的 onPreExecute 方法正在按时调用,这是我在调试时发现的,但在那之后 doInBackground 需要将近 5-7 分钟才能启动。
-
@Lumma 没有使用延迟的帖子。
-
请记住,
AsyncTask调用可能会被序列化,具体取决于您的项目设置和运行的 Android 版本:commonsware.com/blog/2012/04/20/…