开发者

how to download video from server in android

i am doing app for downloading video from server and play the downloaded video from sdcard.

I have a video file on a website in .MP4 format and video downloaded from server and should save in sdcard.

my problem i开发者_运维问答s how to download video from server. please give some ideas and example to me.

please help me.


Android comes with HTTPClient. You should be able to get all the info you need from the HTTPClient website.

Examples: http://hc.apache.org/httpcomponents-client-ga/examples.html

Android API Docs: http://developer.android.com/reference/org/apache/http/client/package-summary.html


Download MP4 video from server in android Using AsyncTask

public class CheckForSDCard {
//Check If SD Card is present or not method
public static boolean isSDCardPresent() {
    if (Environment.getExternalStorageState().equals(

            Environment.MEDIA_MOUNTED)) {
        return true;
    }
    return false;
}}

if (CheckForSDCard.isSDCardPresent()) {

                    //check if app has permission to write to the external storage.
                    if (EasyPermissions.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        //Get the URL entered
                        url =videolist.get(i).optString("video") ;
                        new DownloadFile().execute(url);

                    } else {
                        //If permission is not present request for the same.
                       Utils.checkAndRequestPermissions(getActivity());
                    }


                } else {
                    Toast.makeText(getActivity(),
                            "SD Card not found", Toast.LENGTH_LONG).show();

                }

 private class DownloadFile extends AsyncTask<String, String, String> {


    private String fileName;
    private String folder;
    private boolean isDownloaded;
    File directory;

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        Utils.show(getActivity(),"Downloading Started");
    }

    /**
     * Downloading file in background thread
     */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // getting file length
            int lengthOfFile = connection.getContentLength();


            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            //String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

            //Extract file name from URL
            fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length());

            //Append timestamp to file name
            fileName = fileName;

            //External directory path to save file

            folder = Environment.getExternalStorageDirectory() + File.separator + "Internal Storage/DCIM/Camera/";

            //Create androiddeft folder if it does not exist
            directory = new File(folder);

            if (!directory.exists()) {
                directory.mkdirs();
            }

            // Output stream to write file
            OutputStream output = new FileOutputStream(folder + fileName);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lengthOfFile));
                Log.d(TAG, "Progress: " + (int) ((total * 100) / lengthOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();
            return "Downloaded at: " + folder + fileName;

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return "Something went wrong";
    }

    /**
     * Updating progress bar
     */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage

    }


    @Override
    protected void onPostExecute(String message) {
        // dismiss the dialog after the file was downloaded
        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(directory)));
        // Display File path after downloading
        Toast.makeText(getActivity(),
                "Downloaded Successfully", Toast.LENGTH_LONG).show();
    }
}               
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜