我是android新手。我想将网址中的图像保存到SD卡中。
File direct = new File(Environment.getExternalStorageDirectory()
+ "/.imgapp");
if (!direct.exists()) {
direct.mkdirs();
}
Calendar c = Calendar.getInstance();
int d = c.get(Calendar.DATE);
int d1 = c.get(Calendar.MONTH)+1;
File file = new File(Environment.getExternalStorageDirectory()
+ "/.imgapp/"+d+""+d1+".png" );
if (!file.exists()) {
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()
+ "/.imgapp/"+d+""+d1+".png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally { output.close(); }
} finally { input.close(); }
}else{
Toast.makeText(getApplicationContext(), "No Error", Toast.LENGTH_SHORT).show();
}
清单文件
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我尝试此代码但应用程序停止和崩溃请帮助我。 我想在用户打开App时下载image onCreate。
答案 0 :(得分:0)
终于完成!!。
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
String uRl = "http://bitsparrow.altervista.org/wp-content/uploads/2013/04/5.jpg";
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/.appimg", "test.jpg");
mgr.enqueue(request);
这项工作对我来说..!