ANDROID: How do I download a video file to SD card?

后端 未结 2 1991
孤城傲影
孤城傲影 2020-12-01 01:31

I have a video file on a website in .MP4 format and I want to allow the user to be able to download the video to their SD card by clicking a link. Is there an easy way to d

2条回答
  •  醉梦人生
    2020-12-01 02:27

    aren't running out of memory ? I imagine a video file is very large - which you are buffering before writing to file.

    I know your example code is all over the internet - but it's BAD for downloading ! Use this:

    private final int TIMEOUT_CONNECTION = 5000;//5sec
    private final int TIMEOUT_SOCKET = 30000;//30sec
    
    
                URL url = new URL(imageURL);
                long startTime = System.currentTimeMillis();
                Log.i(TAG, "image download beginning: "+imageURL);
    
                //Open a connection to that URL.
                URLConnection ucon = url.openConnection();
    
                //this timeout affects how long it takes for the app to realize there's a connection problem
                ucon.setReadTimeout(TIMEOUT_CONNECTION);
                ucon.setConnectTimeout(TIMEOUT_SOCKET);
    
    
                //Define InputStreams to read from the URLConnection.
                // uses 3KB download buffer
                InputStream is = ucon.getInputStream();
                BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
                FileOutputStream outStream = new FileOutputStream(file);
                byte[] buff = new byte[5 * 1024];
    
                //Read bytes (and store them) until there is nothing more to read(-1)
                int len;
                while ((len = inStream.read(buff)) != -1)
                {
                    outStream.write(buff,0,len);
                }
    
                //clean up
                outStream.flush();
                outStream.close();
                inStream.close();
    
                Log.i(TAG, "download completed in "
                        + ((System.currentTimeMillis() - startTime) / 1000)
                        + " sec");5
    

提交回复
热议问题