【发布时间】:2021-10-17 10:22:33
【问题描述】:
我正在使用一个应用程序,该应用程序使用 URL 从 Web 下载 mp3 文件并将它们设置在外部存储中创建的文件夹中,它适用于版本 5 (lolipop),但是当我使用版本 8 和 10 对其进行测试时,这不行!
这是下载代码:
String surl="https://media.sd.ma/assabile/recitations_7892537823/mp3/saad-el-ghamidi-001-al-fatiha-204-9244.mp3";
try{
URL url=new URL(surl);
URLConnection conexion=url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
File apkStorage = new File(
Environment.getExternalStorageDirectory() + "/" +"apk_stokage");
if (!apkStorage.exists()) {
apkStorage.mkdir();
}
outputFile=new File(apkStorage,title+".mp3");
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e("apk_stokage","File Created");
}
String path=Environment.getExternalStorageDirectory()+"/apk_stokage/";
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is= new BufferedInputStream(url.openStream());
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
long total=0;
while ((len1 = is.read(buffer)) != -1) {
total+=len1;
publishProgress((int)((total*100)/lenghtOfFile));
fos.write(buffer, 0, len1);//Write new file
}
// fos.flush();
fos.close();
is.close();
// path2=outputFile.getPath();
}catch(Exception e){
e.printStackTrace();
}
【问题讨论】:
-
那么所有这些代码行中的“不起作用”是什么?具体是哪条线?例外?错误?查看 Logcat。
-
请将日志语句放入 catch 块中。
-
apkStorage.mkdir();检查返回值,因为它可能无法创建该目录。如果失败则停止。最好在开始下载之前尝试创建目录。调整您的代码以执行此操作。 -
String path=Environment.getExternalStorageDirectory()+"/apk_stokage/";删除该行,因为您不使用它。 (这很好)。 -
请调整您帖子的主题。不要大喊大叫。
标签: android downloadfile