gpt4 book ai didi

android - 如何从 url 下载 android 中的 mp3 文件并将其保存在 SD 卡中?这是我正在使用的代码

转载 作者:太空狗 更新时间:2023-10-29 15:55:13 25 4
gpt4 key购买 nike

public void DownloadFromUrl(String imageURL, String fileName) {  
//this is the downloader method
try {
URL url = new URL("http://picosong.com/wvaV");
File file = new File(fileName);

long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();

/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}

/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");

} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
}

最佳答案

尝试以下代码下载文件。

private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@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_photo_from_gdansk_poland.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 unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}

并查看下面的链接以获取更多信息。

Download File

关于android - 如何从 url 下载 android 中的 mp3 文件并将其保存在 SD 卡中?这是我正在使用的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13133498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com