如何实现inapp下载mp3文件

How to implement inapp download mp3 file

在我的应用程序中,我有 RecylerView 中的 mp3 文件列表 每个mp3文件都有下载按钮。

我想要的:

How to implement in-app download functionality on click of download button.

在您的 list_item.xml 上创建一个按钮..在该按钮上单击实施此代码..

btn.setOnclickListner(new View.OnClickListner(){ 
      new DownloadFileAsync().execute("your mp3 url from api");
});

创建一个下载文件的异步任务class..

class DownloadFileAsync extends AsyncTask <String, String, String> {
ProgressDialog mProgressDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/some_file.jpg");
            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;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC",progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String progress) {
        mProgressDialog.dismiss();
    }
}