我最近优化了我的 TileProvider 代码以用于离线地图平铺,但我遇到了一个新问题,即在加载地图或跟随 CameraChange 之后,getTile 可能在一分钟内都不会被调用——有时甚至永远不会被调用。
我以这种方式初始化 TileProvider(这是在 setUpMap()、onResume() 中以及在我重置地图或我的离线地图的开/关设置更改时调用的函数中):
if (mapsOn()) customOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider
(new MyTileProvider()));
(我保存为 customOverlay 以便我可以在 onStop() 中调用 customOverlay.clearTileCache() ,否则我似乎有内存问题。)
我的 TileProvider,按照此处的示例,修改为从 zipfile 中获取图块:
public class MyTileProvider implements TileProvider {
private final int TILE_WIDTH = 256;
private final int TILE_HEIGHT = 256;
private static final int BUFFER_SIZE = 16 * 1024;
private String pathToZipFile = MyConstants.TILE_PROVIDER_PATH_PREFIX;
private ZipResourceFile zipFile;
private String currentPath;
public MyTileProvider() {
}
public Tile getTile(int x, int y, int zoom) {
//debug code here shows this is not getting called when the maps are not loading.
//How do I force it to be called?
byte[] image = readTileImage(x, y, zoom);
return image == null ? NO_TILE : new Tile (TILE_WIDTH, TILE_HEIGHT, image);
}
private byte[] readTileImage(int x, int y, int zoom) {
InputStream in = null;
ByteArrayOutputStream buffer = null;
if (zipFile==null) initializeZipFile(x, zoom);
try {
in = zipFile.getInputStream(zoom+"/"+x+"/"+y+".png");
buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[BUFFER_SIZE];
while ((nRead = in.read(data, 0, BUFFER_SIZE)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
} catch (IOException e1) {
e1.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} finally {
if (in!=null) try { in.close(); } catch (Exception ignored) {}
if (buffer != null) try { buffer.close(); } catch (Exception ignored) {}
}
}
public void initializeZipFile(int x, int zoom) {
//code to choose the correct zip file based upon the zoom level and x coordinate
}
}