我正在尝试创建一个应用程序,可以从服务器下载音乐文件,确切地说.mp3.因为我是这个Android开发领域的新手,所以我将感谢你们的任何帮助.我需要一些东西开始,如果你能给我一些有用资源的链接,我将非常感激.谢谢
use*_*305 12
如果您想从任何网址播放.mp3文件,请遵循nik建议的代码.
但是,如果要从服务器下载文件并将其存储在SD卡或内部存储设备上的任何位置,请遵循以下代码:
private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... urlParams) {
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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:清单权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14124 次 |
| 最近记录: |