0

我构建/复制了一个下载功能,该功能通过 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();
4

1 回答 1

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);
于 2013-02-01T11:35:17.987 回答