Android OutOfMemoryError:?

前端 未结 8 1494
孤街浪徒
孤街浪徒 2020-11-28 06:02

I am sporadically getting an OutOfMemoryError: (Heap Size=49187KB, Allocated=41957KB) in one of my apps. What can I do to diagnose this?

  01-09         


        
相关标签:
8条回答
  • 2020-11-28 06:55

    This may happen if the bitmap resource is not disposed correctly. It is better to read the dimensions to see if it fits the memory. http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

    0 讨论(0)
  • 2020-11-28 07:02

    Common fixes:

    1. Fix your contexts:

    Try using the appropiate context: For example since a Toast can be seen in many activities instead of in just one, use getApplicationContext() for toasts, and since services can keep running even though an activity has ended start a service with:

    Intent myService = new Intent(getApplicationContext(), MyService.class)

    Use this table as a quick guide for what context is appropiate:

    Original article on context here.

    2. Check that you're actually finishing your services.

    For example I have an intentService that use google location service api. And I forgot to call googleApiClient.disconnect();:

    //Disconnect from API onDestroy()
        if (googleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, GoogleLocationService.this);
            googleApiClient.disconnect();
        }
    

    3. Check image and bitmaps usage:

    If you are using square's library Picasso I found I was leaking memory by not using the .fit(), that drastically reduced my memory footprint from 50MB in average to less than 19MB:

    Picasso.with(ActivityExample.this)                   //Activity context
                    .load(object.getImageUrl())           
                    .fit()                                //This avoided the OutOfMemoryError
                    .centerCrop()                         //makes image to not stretch
                    .into(imageView);
    

    4. If you are using broadcast receivers unregister them.

    5. If you are using java.util.Observer (Observer pattern):

    Make sure to to use deleteObserver(observer);

    0 讨论(0)
提交回复
热议问题