Android SDK - Downloading of files very slow

2019-09-16 08:09发布

问题:

I built/copied a download function which gets images and videos via an URL and downloads them to an Android device.

When downloading small images it's no problem. But when trying to get files with more than 2MB (via WLAN!) it takes literally ages! About 5 minutes for an 25MB video and so on.

Any ideas what might go wrong?

Here's my code:

        /* 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();

回答1:

Use DownloadManager to download files

        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
                        }

                    }
}
            }
}};

To start this download use:

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