2

I'm creating a simple Android widget that fetches and displays some movie covers from a website. It's simple GridView that displays the images. The widget works fine but the moment I begin scrolling, I get and OutOfMemoryError and Android kills my process.

Here's the code of my RemoteViewsFactory. I can't seem to understand how to resolve this. The images I'm using are properly sized so I don't waste memory in Android. They are perfectly sized. As you can see I'm using a very small LRU cache and in my manifest, I've even enabled android:largeHeap="true". I've racked my head on this issue for a full two days and I'm wondering if what I'm trying to do is even possible?

public class SlideFactory implements RemoteViewsFactory {

    private JSONArray jsoMovies = new JSONArray();
    private Context ctxContext;
    private Integer intInstance;
    private RemoteViews remView;
    private LruCache<String, Bitmap> lruCache;
    private static String strCouch = "http://192.168.1.110:5984/movies/";

    public SlideFactory(Context ctxContext, Intent ittIntent) {
        this.ctxContext = ctxContext;
        this.intInstance = ittIntent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        this.lruCache = new LruCache<String, Bitmap>(4 * 1024 * 1024);
        final Integer intMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final Integer intBuffer = intMemory / 8;

        lruCache = new LruCache<String, Bitmap>(intBuffer) {
            @Override
            protected int sizeOf(String strDigest, Bitmap bmpCover) {
                return bmpCover.getByteCount() / 1024;
            }
        };
    }

    public RemoteViews getViewAt(int intPosition) {
        if (intPosition <= getCount()) {
            try {
                String strDocid = this.jsoMovies.getJSONObject(intPosition).getString("id");
                String strDigest = this.jsoMovies.getJSONObject(intPosition).getJSONObject("value").getJSONObject("_attachments").getJSONObject("thumb.jpg").getString("digest");
                String strTitle = this.jsoMovies.getJSONObject(intPosition).getJSONObject("value").getString("title");
                Bitmap bmpThumb = this.lruCache.get(strDigest);

                if (bmpThumb == null) {
                    String strUrl = strCouch + strDocid + "/thumb.jpg";
                    System.out.println("Fetching" + intPosition);
                    bmpThumb = new ImageFetcher().execute(strUrl).get();
                    this.lruCache.put(strDigest, bmpThumb);
                }
                remView.setImageViewBitmap(R.id.movie_cover, bmpThumb);
                remView.setTextViewText(R.id.movie_title, strTitle);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return remView;
        }
        return null;
    }

    public void onCreate() {
        return;
    }

    public void onDestroy() {
        jsoMovies = null;
    }

    public int getCount() {
        return 20;
    }

    public RemoteViews getLoadingView() {
        return null;//new RemoteViews(this.ctxContext.getPackageName(), R.layout.loading);
    }

    public int getViewTypeCount() {
        return 1;
    }

    public long getItemId(int intPosition) {
        return intPosition;
    }

    public boolean hasStableIds() {
        return true;
    }

    public void onDataSetChanged() {
        this.remView = new RemoteViews(this.ctxContext.getPackageName(), R.layout.slide);
        try {
            DefaultHttpClient dhcNetwork = new DefaultHttpClient();
            String strUrl = strCouch + "_design/application/_view/language?" + URLEncoder.encode("descending=true&startkey=[\"hi\", {}]&attachments=true");
            HttpGet getMovies = new HttpGet(strUrl);
            HttpResponse resMovies = dhcNetwork.execute(getMovies);
            Integer intMovies = resMovies.getStatusLine().getStatusCode();
            if (intMovies != HttpStatus.SC_OK) {
                throw new HttpResponseException(intMovies, "Server responded with an error");
            }
            String strMovies = EntityUtils.toString(resMovies.getEntity(), "UTF-8");
            this.jsoMovies = new JSONObject(strMovies).getJSONArray("rows");
        } catch (Exception e) {
            Log.e("SlideFactory", "Unknown error encountered", e);
        } 
    }
}

Here's the source of the AsyncTask that fetches the images:

public class ImageFetcher extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... strUrl) {
        Bitmap bmpThumb = null;
        try {
            URL urlThumb = new URL(strUrl[0]);
            HttpURLConnection hucConnection = (HttpURLConnection) urlThumb.openConnection();
            InputStream istThumb = hucConnection.getInputStream();
            bmpThumb = BitmapFactory.decodeStream(istThumb);
            istThumb.close();
            hucConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bmpThumb;
    }
}
4

2 回答 2

2

我有类似的痛苦经历,经过大量挖掘后,我发现将setImageViewBitmap所有位图复制到新实例中,因此占用了双倍内存。考虑将以下行更改为静态资源或其他内容!

remView.setImageViewBitmap(R.id.movie_cover, bmpThumb);

这需要大量内存并 ping 垃圾收集器来清理内存,但速度太慢以至于您的应用程序无法及时使用释放的内存。

于 2013-11-26T06:17:55.610 回答
0

我的解决方法是使用 LRUCache 来存储小部件的位图:

首先,像往常一样初始化:

protected void initializeCache()
    {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        // Use 1/10th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 10;

        bitmapLruCache = new LruCache<String, Bitmap>(cacheSize)
        {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };
    }

然后重用位图:

void updateImageView(RemoteViews views, int resourceId, final String imageUrl)
    {
        Bitmap bitmap = bitmapLruCache.get(imageUrl);

        if (bitmap == null)
        {
            bitmap = // get bitmap from web with your loader
            bitmapLruCache.put(imageUrl, bitmap);
        }

        views.setImageViewBitmap(resourceId, bitmap);
    }

使用此代码小部件现在不会使我的应用程序崩溃。

更多信息在这里

于 2015-10-27T07:42:23.223 回答