1. 程式人生 > >如何利用LRUCache製作安卓端谷歌地圖的三級快取

如何利用LRUCache製作安卓端谷歌地圖的三級快取

第一個檔案,繼承ArcGIS的TileServerLayer

/**
 *
 * @author wjf
 * @date 2018/09/30
 */

public class GoogleMapLayer extends TiledServiceLayer {
    private static  final int MAXLRU_SIZE=1024*1024*8*1;//假設為1M;
    private final int MIN_LEVEL = 0;//設定縮放的最小級別
    private final int MAX_LEVEL = 19;//設定縮放的最大級別,這裡最大層級19,可以自定義(需要在下方的 MAP_SCALE 和 RESOLUTIONS 中設定相對應的資料)
    private int GoogleMapLayerType;
    private MapCacheHelper cacheHelper;
    private double[] MAP_SCALE = new double[]{591657527.591555,
            295828763.79577702, 147914381.89788899, 73957190.948944002,
            36978595.474472001, 18489297.737236001, 9244648.8686180003,
            4622324.4343090001, 2311162.217155, 1155581.108577, 577790.554289,
            288895.277144, 144447.638572, 72223.819286, 36111.909643,
            18055.954822, 9027.9774109999998, 4513.9887049999998, 2256.994353,
            1128.4971760000001};
    private double[] RESOLUTIONS = new double[]{156543.03392800014,
            78271.516963999937, 39135.758482000092, 19567.879240999919,
            9783.9396204999593, 4891.9698102499797, 2445.9849051249898,
            1222.9924525624949, 611.49622628138, 305.748113140558,
            152.874056570411, 76.4370282850732, 38.2185141425366,
            19.1092570712683, 9.55462853563415, 4.7773142679493699,
            2.3886571339746849, 1.1943285668550503, 0.59716428355981721,
            0.29858214164761665};
    private Point ORIGIN_PNT = new Point(-20037508.342787, 20037508.342787);
    private int DPI = 96;
    private int TILEWIDTH = 256;
    private int TILEHEIGHT = 256;
    public GoogleMapLayer(int layerType) {
        super(true);
        this.GoogleMapLayerType = layerType;
        this.init();
    }
    private void init() {
        try {
            getServiceExecutor().submit(() -> GoogleMapLayer.this.initLayer());
            // 這裡是設定快取到本地的路徑 可以自定義
            String imgPtPath = AppConsts.CACHE_DIR + "/t" + GoogleMapLayerType + "/";
            cacheHelper=new MapCacheHelper(GoogleMapLayerType,MAXLRU_SIZE,imgPtPath);
        } catch (RejectedExecutionException rejectedexecutionexception) {
            Log.e("Google Map Layer", "initialization of the layer failed.", rejectedexecutionexception);
        }
    }
   @Override
    protected byte[] getTile(int level, int col, int row) throws Exception {
        byte[] res;
        if (level > MAX_LEVEL || level < MIN_LEVEL) {
            return new byte[0];
        }
        String s = "Galileo".substring(0, ((3 * col + row) % 8));
        String url = getMapUrl(level,col,row,s);
        //開始獲取三級快取1、記憶體
       if((res=cacheHelper.getMapCache(url))!=null){
           return res;
       }else if((res=cacheHelper.getLocalMapCache(level,col,row))!=null){
           cacheHelper.setMapCache(url,res);
           return res;
       }else{
           if (isNetworkAvailable(MyApp.getContext())) {
               Map<String, String> map = null;
               res= com.esri.core.internal.io.handler.a.a(url, map);
               cacheHelper.setLocalMapCache(level,col,row,res);
               cacheHelper.setMapCache(url,res);
               return res;
           }else{

           }
       }
       return new byte[0];
    }
    protected SpatialReference getSptialReference() {
        return this.getDefaultSpatialReference();
    }
    @Override
    protected void initLayer() {
        if (getID() == 0L) {
            nativeHandle = create();
            changeStatus(com.esri.android.map.event.OnStatusChangedListener.STATUS.fromInt(-1000));
        } else {
            this.setDefaultSpatialReference(SpatialReference.create(102113));
            this.setFullExtent(new Envelope(-20037508.34, -20037508.34, 20037508.34, 20037508.34));
            this.setTileInfo(new TileInfo(ORIGIN_PNT, MAP_SCALE, RESOLUTIONS, MAP_SCALE.length, DPI, TILEWIDTH, TILEHEIGHT));
            super.initLayer();
        }
    }
    private  boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }
        return true;

    }
    public String getMapUrl(int level, int col, int row,String s){
        String url="";
        switch (GoogleMapLayerType) {
            case GoogleMapLayerTypes.IMAGE_GOOGLE_MAP:
                url = "http://mt" + (col % 4) + ".google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&" +
                        "x=" + col + "&" +
                        "y=" + row + "&" +
                        "z=" + level + "&" +
                        "s=" + s;
                break;
            case GoogleMapLayerTypes.VECTOR_GOOGLE_MAP:
                url = "http://mt2.google.cn/vt/
[email protected]
&hl=zh-CN&gl=cn&" + "x=" + col + "&" + "y=" + row + "&" + "z=" + level + "&" + "s=" + s; break; case GoogleMapLayerTypes.TERRAIN_GOOGLE_MAP: url = "http://mt" + (col % 4) + ".google.cn/vt/
[email protected]
,[email protected]&hl=zh-CN&gl=cn&" + "x=" + col + "&" + "y=" + row + "&" + "z=" + level + "&" + "s=" + s; break; case GoogleMapLayerTypes.ANNOTATION_GOOGLE_MAP: url = "http://mt" + (col % 4) + ".google.cn/vt/imgtp=png32&
[email protected]
&hl=zh-CN&gl=cn&" + "x=" + col + "&" + "y=" + row + "&" + "z=" + level + "&" + "s=" + s; break; } return url; } }

第二個檔案:

public interface GoogleMapLayerTypes {
    /**
     * 谷歌向量地圖服務
     */
    int VECTOR_GOOGLE_MAP = 1;
    /**
     * 谷歌影像地圖服務
     */
    int IMAGE_GOOGLE_MAP = 2;
    /**
     * 谷歌地形地圖服務
     */
    int TERRAIN_GOOGLE_MAP = 3;
    /**
     * 谷歌道路等POI地圖服務
     */
    int ANNOTATION_GOOGLE_MAP = 4;
}
第三個檔案  實現快取
**
 * @author:wjf
 * @date:20180930
 * 為谷歌地圖配置相對應的
 */
public class MapCacheHelper {
    private int GoogleMapLayerType;
    LruCache<String,byte[]> myLruCache;
    String filePath;

    /**
     *
     * @param googleMapLayerType  地圖型別
     * @param mapLRUCapacity   LRUCache的大小
     * @param filePath 存放本地快取的路徑
     */
    public MapCacheHelper(int googleMapLayerType, int mapLRUCapacity, String filePath){
        this.GoogleMapLayerType=googleMapLayerType;
        this.filePath=filePath;
        FileUtils.createDirs(filePath);
        myLruCache=new LruCache<String,byte[]>(mapLRUCapacity){
            @Override
            protected int sizeOf(String key, byte[] value) {
                return value.length;
            }
        };
    }
    public byte[] getMapCache(String url){
        return myLruCache.get(url);
    }
    public void setMapCache(String url,byte[] data){
        myLruCache.put(url,data);
    }
    private byte[] getLocalMapCache(String imgPath,String imgName){
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath + imgName);
        if(bitmap==null) return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    public byte[] getLocalMapCache(int level, int col, int row){
        String imgPath = filePath+ "l" + level + "/";
        String imgName = "c" + col + "r" + row + ".png";
        return getLocalMapCache(imgPath,imgName);
    }
    private void saveFile(String filePath, byte[] data, String fileName) throws IOException {
        Bitmap mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        // 檢測是否有 .nomedia 檔案,該檔案防止相簿等媒體軟體掃描離線地圖圖片,以免造成不必要的麻煩
        File nomediaFile = new File(filePath + ".nomedia");
        if (!nomediaFile.exists()) {
            nomediaFile.createNewFile();
        }
        File myCaptureFile = new File(filePath + fileName);
        // 判斷離線的圖片是否已經存在,已經存在的地圖不用再次下載(節省流量)
        if (myCaptureFile.exists()) {
            return;
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        mBitmap.compress(Bitmap.CompressFormat.PNG, 80, bos);
        bos.flush();
        bos.close();
    }
    public void setLocalMapCache(int level, int col, int row, byte[] data){
        try {
            String imgPath = filePath+ "l" + level + "/";
            String imgName = "c" + col + "r" + row + ".png";
            saveFile(imgPath,data, imgName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}