Android中的文件下载[关闭]

幽映每白日,清辉照衣裳。这篇文章主要讲述Android中的文件下载[关闭]相关的知识,希望能为你提供帮助。
我想创建一个音乐播放器

  • 有列表项
  • 点击每个项目
  • 从url下载.amr文件,在文件夹中播放音乐播放器中保存的文件
如何创建onclick下载文件?
答案是,使用AsyncTask并在对话框中显示下载进度:
【Android中的文件下载[关闭]】//将对话框声明为您的活动ProgressDialog mProgressDialog的成员字段;
//在onCreate方法中实例化它
mProgressDialog = new ProgressDialog(YourActivity.this); mProgressDialog.setMessage("A message"); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); DownloadFile downloadFile = new DownloadFile(); downloadFile.execute("Put here the URL .amr file"); private class DownloadFile extends AsyncTask< String, Integer, String> { @Override protected String doInBackground(String... sUrl) { try { URL url = new URL(sUrl[0]); URLConnection connection = url.openConnection(); connection.connect(); // this will be useful so that you can show a typical 0-100% progress bar int fileLength = connection.getContentLength(); // download the file InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream("/sdcard/file_name.extension"); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); }output.flush(); output.close(); input.close(); } catch (Exception e) { } return null; }@Override protected void onPreExecute() { super.onPreExecute(); mProgressDialog.show(); }@Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); mProgressDialog.setProgress(progress[0]); }

}

    推荐阅读