【问题标题】:Android SDK - Downloading of files very slowAndroid SDK - 文件下载速度很慢
【发布时间】:2013-02-01 11:04:37
【问题描述】:

我构建/复制了一个下载功能,该功能通过 URL 获取图像和视频并将它们下载到 Android 设备。

下载小图片时没问题。但是当试图获取超过2MB 的文件(通过WLAN!)时,它确实需要很长时间!一个 25MB 的视频大约需要 5 分钟,以此类推。

有什么想法可能会出错吗?

这是我的代码:

        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
                baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

【问题讨论】:

  • 也许有缓冲区大小的东西....使用下载管理器....最好的下载方式
  • 谢谢,但你能提供一些代码或链接吗?
  • 看下面有一个例子
  • 我认为你应该增加读取缓冲区。 50 字节真的很差
  • 最好是 2k, 4k:) (2048, 4096)。

标签: android http download


【解决方案1】:

使用 DownloadManager 下载文件

        private long enqueue;
private DownloadManager dm;

 BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();


            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                Query query = new Query();
                query.setFilterById(enqueue);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                        Log.e("Download completed","HERE DOWNLOAD COMPLETED");
                        try
                        {
                                                        }
                        catch (Exception e) {
                            // TODO: handle exception
                        }

                    }
}
            }
}};

要开始下载,请使用:

         dm = (DownloadManager)activityContext.getSystemService(activityContext.DOWNLOAD_SERVICE);
    Request request = new Request(Uri.parse("URL")).setDestinationInExternalPublicDir("DIRECTORY","FILENAME");
    enqueue = dm.enqueue(request);

【讨论】:

猜你喜欢
  • 2016-12-18
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2013-01-15
相关资源
最近更新 更多