Android GroundoverLay消耗大量内存

时间:2018-03-23 09:38:40

标签: android google-maps

我正在使用Android Weather应用程序,我的要求是显示动画预测。我们有一台服务器,我使用Glide将预测图像加载为Bitmap,然后使用位图创建GoogleMap的GroundOveryayOption。 我正在使用Runnable和Handler进行动画制作。

除了内存消耗之外,一切都运行良好,最终我得到了“Out of memory exception”

为了顺利运行我的预测动画,我必须使用Glide加载所有位图并从Bitmap创建GroundOverlayOptions obj并在HashMap中存储GroundOverlayOptions,如下所示。

    @Override
            public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                mBitmapLoaded = true;

//the actual image is png and its size is in KBs but Bitmap size is in MBs
                Log.i("Weather", ""+ bitmap.getByteCount());

                GroundOverlayOptions overlayOptions = new GroundOverlayOptions()
                        .image(BitmapDescriptorFactory.fromBitmap(bitmap))
                        .positionFromBounds(getLatLngBounds(mBounds))
                        .visible(frameVisible);

    //groundOverlaysItemMap is a Hashmap to store GroundOverlayOptions where key is Time
                groundOverlaysItemMap.put(mTime, mMap.addGroundOverlay(overlayOptions));
            }

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

将“大”图片拆分为“小”(例如256x256像素)图块(例如MapTiler视频中的this),将其保存到raw文件夹(或设备存储)并使用TileProviderthat回复中的Alex Vasilkov

public class CustomMapTileProvider implements TileProvider {
    private static final int TILE_WIDTH = 256;
    private static final int TILE_HEIGHT = 256;
    private static final int BUFFER_SIZE = 16 * 1024;

    private AssetManager mAssets;

    public CustomMapTileProvider(AssetManager assets) {
        mAssets = assets;
    }

    @Override
    public Tile getTile(int x, int y, int zoom) {
        byte[] image = readTileImage(x, y, zoom);
        return image == null ? null : new Tile(TILE_WIDTH, TILE_HEIGHT, image);
    }

    private byte[] readTileImage(int x, int y, int zoom) {
        InputStream in = null;
        ByteArrayOutputStream buffer = null;

        try {
            in = mAssets.open(getTileFilename(x, y, zoom));
            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 e) {
            e.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) {}
        }
    }

    private String getTileFilename(int x, int y, int zoom) {
        return "map/" + zoom + '/' + x + '/' + y + ".png";
    }
}