java - 下载文件导致 UI 卡顿

标签 java android multithreading

我有一项服务可以在 AysncTaskdoInBackground() 方法中下载一个大文件:

data = new byte[8192];
output = new FileOutputStream(fileLoc);
connection = (HttpURLConnection) new URL(currUrl).openConnection();
input = new BufferedInputStream(connection.getInputStream());
while ((count = input.read(data)) != -1) {
    output.write(data, 0, count);
}

当它正在执行时(文件正在下载),在 ListView 中滚动可能会有点断断续续到非常断断续续。

我已经尝试为下载服务创建一个新进程,更改 doInBackground() 线程的优先级,在 while 循环期间暂停任意毫秒数并且我针对内存使用情况进行了优化。

我被卡住了,不知道如何才能让 UI 在下载过程中不卡顿。下载未进行时 UI 正常响应...

最佳答案

documentation说:

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

因此请考虑在您的服务中使用 Thread。或者看看 IntentService ,它在单独的工作线程上运行并且不影响 UI(避免 NetworkOnMainThreadException )。关于 IntentService 的注意事项:

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

UI 是另一部分。如果您可以提供您的方法,我想也许我可以提供帮助。 例如,my app 中的下载扩展到目前为止工作正常:-)

关于java - 下载文件导致 UI 卡顿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349496/

相关文章:

在 bin\javaw.exe 中找不到 Java 运行时环境

java - BigQuery - 通过 java 进行流式传输非常慢

java - 为什么我在实现 GestureDetector 时出错?

python - 带后台线程的flask应用程序

Java:执行Runnable固定次数

java - java中的PubSub模型

java - RecyclerView onCreateViewHolder位置背景颜色

android - 显示抽屉导航时明确关注内容

java - 在多个java线程之间共享数据并获取更新值

linux - Windows 中的线程亲和性