gpt4 book ai didi

Android:Asynctask 的doInBackground 方法在长时间延迟后被调用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:00:29 24 4
gpt4 key购买 nike

我一直在尝试从 url 下载视频,我已经在 asynctask 的 doInBackground() 中实现了我的下载方法,但是 doInBackground 方法需要很长时间才能被调用(5-10 分钟),我是使用另一个异步任务下载 Activity 中的图像,我从中被引导下载视频 Activity 及其工作正常。我的 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);
}
}

最佳答案

确保没有其他 asyncTasks 正在运行,如果需要可以取消它们。

在大多数 android 版本上,asyncTask 在单个后台线程上运行,并且应该只运行小任务。

如果任务可能花费太长时间(或有多个任务),请考虑取消它们或使用替代方法(如使用 executeOnExecutor,如 on the API 所述)。

关于Android:Asynctask 的doInBackground 方法在长时间延迟后被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com