我正在开发一个APP,需要从网上下载一个文件并存储在SDCard上。我注意到有些设备在下载时会报告错误,例如“解析错误”。我假设某些设备没有 SDCard,或者我在课堂上获得的路径不正确。如果没有 SDCard 或未安装,支持所有设备的最安全方法是什么?这是我的代码:
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Download/file.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
我认为问题可能出在这一行:
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Download/file.apk");
我应该使用getExternalStorageDirectory() 并下载吗?或者是否有所有设备通用的“最安全”位置?