【发布时间】:2014-02-05 08:34:21
【问题描述】:
当我点击按钮时,我想通过 url 从我的服务器下载音频。
我是怎么做到的?
【问题讨论】:
-
你的问题不清楚。你想做什么?
-
谢谢先生,当我点击按钮时,我想通过 url 从我的服务器下载音频。
当我点击按钮时,我想通过 url 从我的服务器下载音频。
我是怎么做到的?
【问题讨论】:
对于从服务器下载文件,您可以使用以下代码。
private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL("url of your .mp3 file");
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
清单权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
还可以参考以下链接,它可能会对您有所帮助:
how can i download audio file from server by url
Android:How to download the File from the server and save it in specific folder in sdcard
【讨论】: