【问题标题】:How to download a music files from a server using an android app?如何使用安卓应用从服务器下载音乐文件?
【发布时间】:2014-07-30 06:50:52
【问题描述】:

您好我正在尝试开发一个应用程序,该应用程序从特定服务器下载音乐文件并将下载的文件保存在本地,它应该在本地播放。我是 android 的初学者,任何人都可以帮助我任何想法和任何资源。提前致谢。

【问题讨论】:

标签: android audio-player android-music-player


【解决方案1】:

试试这个..

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

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

    /**
     * Downloading file in background thread
     * */
    @Override
    protected File doInBackground(Void... params) {
        int count;
        File file;
        try {
            URL url = new URL(fileUrl);
            URLConnection conection = url.openConnection();
            conection.connect();

            int lenghtOfFile = conection.getContentLength();

            InputStream input = conection.getInputStream();

            File SDCardRoot = Environment.getExternalStorageDirectory();

            File folder = new File(SDCardRoot, "FolderName");
            if (!folder.exists())
                folder.mkdir();
            file = new File(folder, "FileName");

            OutputStream output = new FileOutputStream(file);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;

                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                output.write(data, 0, count);
            }

            output.flush();

            output.close();
            input.close();

        } catch (Exception e) {
            return null;
        }
        return file;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(File file) {
        // dismiss the dialog after the file was downloaded
        dismissProgressDialog();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多