[英]Android - Download File From The Internet to SDCard - Safest Approach
我正在开发一个需要从Internet下载文件并将其存储在SDCard上的APP。 我注意到有些设备在下载时会报告错误,例如“解析错误”。 我假设某些设备没有SDCard,或者我在课堂上得到的路径不正确。 如果没有SDCard或未安装SD卡,支持所有设备的最安全方法是什么? 这是我的代码:
/**
* 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()并下载吗? 还是所有设备都通用的“最安全”位置?
首先,您不想使用AsyncTask下载文件。 因为如果用户杀死了托管任务的屏幕,下载也将被终止。 查看IntentService。
其次,在此处熟悉Android代码示例: http : //developer.android.com/guide/topics/data/data-storage.html#filesExternal
您可以检查可用的内容,然后获取适当的目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.