I recently optimized my TileProvider code for an offline map tiling and I have a new problem where getTile may not be called for up to a minute--and occasionally never--after loading the map or following a CameraChange.
I initialize the TileProvider this way (this is in setUpMap(), onResume(), and within a function that I call if I reset the map or if my offline map's on/off setting is changed):
if (mapsOn()) customOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider
(new MyTileProvider()));
(I save as customOverlay so that I can call customOverlay.clearTileCache() in onStop() because otherwise I seem to have memory problems.)
And my TileProvider, following the example here, modified to fetch tiles from a 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
}
}