Domanda

Hi am trying to develop an app which downloads music files from a particular server and save that downloaded files locally and it should play locally.Am a beginner in android can anyone help me with any idea and any resources.Thanks in advance.

È stato utile?

Soluzione

Try this ..

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

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top