在我的应用中,我有RecylerView
中的mp3文件列表
每个mp3文件都有下载按钮。
我想要的是什么:
如何通过点击下载实现应用内下载功能 按钮。
答案 0 :(得分:2)
在list_item.xml
上创建一个按钮..在该按钮上单击实现此代码..
btn.setOnclickListner(new View.OnClickListner(){
new DownloadFileAsync().execute("your mp3 url from api");
});
创建一个下载文件的异步任务类..
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();
}
}