我正在开发一个带谷歌地图的Android项目,它有谷歌地图标记的自定义图像。但不是每次下载图像,第一次将标记图像下载到内部存储器,从第二次开始我检查图像是否已下载,然后从内存中检索它们。
但是我的手机上的代码运行正常(Android版本2.6.3),但是当我尝试更新的设备(Android 4及更高版本)时,检索下载的位图图像的代码将返回null。
检查图像是否已下载的代码:
public void checkcategoryimagesavailable() {
path_file=MainActivity.this.getFilesDir().getAbsolutePath();
for(int i=0;i<catprearr.size();i++) {
File file = new File(path_file+File.separator+catprearr.get(i)+".png");
if(file.exists()) {
} else {
downloadfile(URL_image+catprearr.get(i)+".png",path_file+File.separator+catprearr.get(i)+".png");
}
}
setvaluesonmap();
}
下载图片的代码:
public void downloadfile(String path,String filepath) {
try {
URL url = new URL(path);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File file = new File(filepath);
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
} catch(Exception e) {
e.printStackTrace();
}
}
设置标记的代码:
public void setvaluesonmap() {
for(int i=0;i<list.size();i++) {
final Store_data s=list.get(i);
Bitmap obj=getImageBitmap(MainActivity.this,s.category+".png");
obj=Bitmap.createScaledBitmap(obj,68,62,false);
iv_category_logo.setImageBitmap(obj);
googleMap.addMarker(new MarkerOptions().title(s.store_name)
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(MainActivity.this, custom_layout)))
.position(new LatLng(Double.parseDouble(s.store_latitude),Double.parseDouble(s.store_longitude))));
}
}
检索下载图像的代码:这是有问题的代码:位图在较新的设备上返回null
public Bitmap getImageBitmap(Context context,String name) {
try {
// FileInputStream fis = context.openFileInput(name);
// File file = new File("filesdir", name);
File myFile = new File (path_file+File.separator+name);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
Bitmap b = BitmapFactory.decodeStream(fis);
//fis.close();
return b;
} catch(Exception e) {
return null;
}
}
为什么它在旧设备上运行良好,但不适用于较新的设备。