如何在android中从服务器下载视频

发布于 2024-11-24 02:12:05 字数 173 浏览 7 评论 0原文

我正在做一个应用程序,用于从服务器下载视频并播放从 SD 卡下载的视频。

我在网站上有一个 .MP4 格式的视频文件,视频是从服务器下载的,应该保存在 SD 卡中。

我的问题是如何从服务器下载视频。请给我一些想法和例子。

请帮我。

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 is how to download video from server. please give some ideas and example to me.

please help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘心安 2024-12-01 02:12:05

Android 自带了 HTTPClient。您应该能够从 HTTPClient 网站 获取所需的所有信息。

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

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

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

梨涡 2024-12-01 02:12:05

在android中使用AsyncTask从服务器下载MP4视频

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();
    }
}               

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();
    }
}               
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文