缓存谷歌地图v2标记位图

时间:2014-02-01 22:45:27

标签: java android google-maps bitmap

这会有点长,但是如果你能忍受我的话我会很感激,我相信这对其他人也很有用。

我在我的Android应用中使用谷歌地图放置不同的标记。每个标记属于由位图表示的类别。我一直在使用Displaying Bitmaps Efficiently中的 BitmapFun 示例来缓存我的应用中的位图,并尝试使用我的Google地图标记实现相同的解决方案。

我的代码已添加到示例的ImageWorker.java中,如下所示(BitmapWorkerTask已存在且已更新以处理标记):

private static Map<Marker, BitmapWorkerTask> markerToTaskMap = new HashMap<Marker, BitmapWorkerTask>();

public void loadImage(Object data, Marker marker) {
    if (data == null) {
        return;
    }

    BitmapDrawable value = null;

    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(String.valueOf(data));
    }

    if (value != null) {
        // Bitmap found in memory cache
        marker.setIcon(BitmapDescriptorFactory.fromBitmap(value.getBitmap()));
    } else if (cancelPotentialWork(data, marker)) {
        final BitmapWorkerTask task = new BitmapWorkerTask(marker);
        markerToTaskMap.put(marker, task);

        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, data);
    }
}

private class BitmapWorkerTask extends AsyncTask<Object, Void, BitmapDrawable> {
    private Object data;
    private WeakReference<ImageView> imageViewReference = null;
    private WeakReference<Marker> markerReference = null;

    public BitmapWorkerTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    public BitmapWorkerTask(Marker marker) {
        markerReference = new WeakReference<Marker>(marker);
    }

    /**
     * Background processing.
     */
    @Override
    protected BitmapDrawable doInBackground(Object... params) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "doInBackground - starting work");
        }

        data = params[0];
        final String dataString = String.valueOf(data);
        Bitmap bitmap = null;
        BitmapDrawable drawable = null;

        // Wait here if work is paused and the task is not cancelled
        synchronized (mPauseWorkLock) {
            while (mPauseWork && !isCancelled()) {
                try {
                    mPauseWorkLock.wait();
                } catch (InterruptedException e) {}
            }
        }

        // If the image cache is available and this task has not been cancelled by another
        // thread and the ImageView that was originally bound to this task is still bound back
        // to this task and our "exit early" flag is not set then try and fetch the bitmap from
        // the cache
        if (mImageCache != null && !isCancelled() && (getAttachedImageView() != null || getAttachedMarker() != null)
                && !mExitTasksEarly) {
            bitmap = mImageCache.getBitmapFromDiskCache(dataString);
        }

        // If the bitmap was not found in the cache and this task has not been cancelled by
        // another thread and the ImageView that was originally bound to this task is still
        // bound back to this task and our "exit early" flag is not set, then call the main
        // process method (as implemented by a subclass)
        if (bitmap == null && !isCancelled() && (getAttachedImageView() != null || getAttachedMarker() != null)
                && !mExitTasksEarly) {
            bitmap = processBitmap(params[0]);
        }

        // If the bitmap was processed and the image cache is available, then add the processed
        // bitmap to the cache for future use. Note we don't check if the task was cancelled
        // here, if it was, and the thread is still running, we may as well add the processed
        // bitmap to our cache as it might be used again in the future
        if (bitmap != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                // Running on Honeycomb or newer, so wrap in a standard BitmapDrawable
                drawable = new BitmapDrawable(mResources, bitmap);
            } else {
                // Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable
                // which will recycle automagically
                drawable = new RecyclingBitmapDrawable(mResources, bitmap);
            }

            if (mImageCache != null) {
                mImageCache.addBitmapToCache(dataString, drawable);
            }
        }

        if (BuildConfig.DEBUG) {
            Log.d(TAG, "doInBackground - finished work");
        }

        return drawable;
    }

    /**
     * Once the image is processed, associates it to the imageView
     */
    @Override
    protected void onPostExecute(BitmapDrawable value) {
        // if cancel was called on this task or the "exit early" flag is set then we're done
        if (isCancelled() || mExitTasksEarly) {
            value = null;
        }

        if (imageViewReference != null) {
            final ImageView imageView = getAttachedImageView();
            if (value != null && imageView != null) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "onPostExecute - setting bitmap");
                }
                setImageDrawable(imageView, value);
            }
        } else if (markerReference != null) {
            final Marker marker = getAttachedMarker();
            if (value != null && marker != null) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "onPostExecute - setting marker bitmap");
                }
                markerToTaskMap.remove(marker);
                marker.setIcon(BitmapDescriptorFactory.fromBitmap(value.getBitmap()));
            }
        }
    }

    @Override
    protected void onCancelled(BitmapDrawable value) {
        super.onCancelled(value);
        synchronized (mPauseWorkLock) {
            mPauseWorkLock.notifyAll();
        }
    }

    /**
     * Returns the ImageView associated with this task as long as the ImageView's task still
     * points to this task as well. Returns null otherwise.
     */
    private ImageView getAttachedImageView() {
        if (imageViewReference == null) {
            return null;
        }

        final ImageView imageView = imageViewReference.get();
        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);

        if (this == bitmapWorkerTask) {
            return imageView;
        }

        return null;
    }

    private Marker getAttachedMarker() {
        if (markerReference == null) {
            return null;
        }

        final Marker marker = markerReference.get();
        final BitmapWorkerTask bitmapWorkerTask = markerToTaskMap.get(marker); //getBitmapWorkerTask(marker);

        if (this == bitmapWorkerTask) {
            return marker;
        }

        return null;
    }
}

public static boolean cancelPotentialWork(Object data, Marker marker) {
    final BitmapWorkerTask bitmapWorkerTask = markerToTaskMap.get(marker);

    if (bitmapWorkerTask != null) {
        final Object bitmapData = bitmapWorkerTask.data;
        if (bitmapData == null || !bitmapData.equals(data)) {
            bitmapWorkerTask.cancel(true);
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "cancelPotentialWork - cancelled work for " + data);
            }
        } else {
            // The same work is already in progress.
            return false;
        }
    }
    return true;
}

如果您熟悉BitmapFun示例,您可以看到一切都与使用带有ImageView的位图几乎相同,只是使用AsyncDrawable将位图连接到其加载的AsyncTask。由于我无法扩展Marker类(它是最终的)并且没有getIcon()方法,所以我必须维护一个hashmap(markerToTaskMap)来完成这项工作。

这个解决方案似乎一般都有效,除了一些毛刺,我得到一个错误的位图作为标记。我不知道为什么。 OOB示例代码不会发生这种情况。

感谢有人在这里帮助我。感谢。

1 个答案:

答案 0 :(得分:3)

我可以通过要求不要这样做来帮助你。

如果你想优化,更好地了解你的敌人。每次调用Google Maps Android API v2都会转到其他进程。其中大部分需要在主线程上完成。

因为对API的每次调用都是同步到达其他进程,所以它将阻止用户界面。例如。在体面的手机上添加2000个标记需要1秒钟(测试过)。另一方面,加载20个小位图来表示onCreate中的类别将花费不到100毫秒(未经测试的声明)。因此,您的代码甚至会降低速度,因为您至少有2次调用才能添加MarkeraddMarkersetIcon

只需使用Bitmap将所有BitmapDescriptorFactory.fromResource加载到Map<Category, BitmapDescriptor>一次,然后在创建Marker时使用它们。

总结一下:除非出现问题,否则不要进行优化。