optimize android code snippet - better design approach?

怎甘沉沦 提交于 2019-12-13 12:51:07

问题


I've this snippet of code which I would like to optimize it. I've a method which is been called regularly by the OSMdroid library to load tons of maptiles. This method directly invokes the filestream and load the bitmap directly and will return the bitmap once loaded on the main UI thread.

Although I've managed to run in the background using AsyncTask with parallel executor. Sometimes with plenty number of overlays (itemized) in the mapview this snippet of code runs slower as GC_FO_ALLOC is triggered regularly for allocation, and in my log messages I get Grow Heap (frag case). I tried many ways to work around, but not effective enough. For some reason this task is being executed on main thread is my feeling as in my log messages I also get Skipped xx frames, the application may be doing lot of task. Any idea how can this be made better? The thing is method has to return back, as soon as it loads, there by how can I allow this method to wait until mapview is not panned or zoomed, then load the tiles?

@SuppressWarnings("deprecation")
    @Override
    public Drawable getDrawable(final InputStream aFileInputStream) throws LowMemoryException {

        try {
            df = new DisplayFile();
            df.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aFileInputStream);
            return new BitmapDrawable(df.get());
        } catch (final OutOfMemoryError e) {
            System.gc();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

private class DisplayFile extends AsyncTask<InputStream, Bitmap, Bitmap> {

        InputStream path;

        @Override
        protected Bitmap doInBackground(InputStream... arg0) {
            path = arg0[0];
            BitmapFactory.Options mBitOpt = new BitmapFactory.Options();
            mBitOpt.inDither = false;
            mBitOpt.inSampleSize = 1;
            mBitOpt.inPurgeable = true;
            mBitOpt.inInputShareable = true;
            mBitOpt.inPreferredConfig = Bitmap.Config.ARGB_8888;
            final Bitmap mBitmap = BitmapFactory.decodeStream(path,null,mBitOpt);
            return mBitmap;
        }
    }

回答1:


As far as I understand, you are trying to display an offline map using osmdroid.

Android is unable to load "tons of map tiles" in memory, because it just doesn't provide enough memory heap to each application.

This is why osmdroid has advanced mechanisms (background loading, LRU cache, ...)

Why are you not just using these standard osmdroid mechanisms?

Look at this post for more details about off-line maps on osmdroid: Download maps for osmdroid



来源:https://stackoverflow.com/questions/23868345/optimize-android-code-snippet-better-design-approach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!