Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of avoiding memory overflow in Android

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the method to avoid memory overflow in Android". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the method to avoid memory overflow in Android".

The way to avoid memory overflow is to optimize the program in the following three aspects

Memory reference

Before dealing with memory references, let's review what are strong references, soft references, weak references, and virtual references.

Strong references: strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never reclaim it. When the memory space is insufficient, the Java virtual machine would rather throw an OutOfMemoryError error to make the program terminate abnormally, rather than solve the problem of insufficient memory by randomly recycling objects with strong references.

Soft reference: if an object has only a soft reference but has enough memory space, the garbage collector will not reclaim it; it will not be reclaimed until the virtual machine reports that it is out of memory, as long as the garbage collector does not reclaim it. The object can be used by the program. Soft references can be used to implement memory-sensitive caching. A soft reference can be used in conjunction with a reference queue (ReferenceQueue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java virtual machine will add the soft reference to the reference queue associated with it.

Weak references: objects with only weak references have a shorter life cycle. When the garbage collector thread scans the memory area under its jurisdiction, once an object with only weak references is found, its memory will be reclaimed regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, objects with only weak references will not necessarily be found quickly. A weak reference can be used in conjunction with a reference queue (ReferenceQueue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.

Virtual references: virtual references can be understood as fictitious references, and unlike other references, virtual references do not determine the life cycle of an object. If an object holds only a virtual reference, it can be reclaimed by the garbage collector at any time as if it had no reference at all. Virtual references are mainly used to track the activity of objects being reclaimed by the garbage collector. One difference between virtual references and soft and weak references is that virtual references must be used in conjunction with reference queues (ReferenceQueue). When the garbage collector is ready to recycle an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can know whether the referenced object is going to be garbage collected by determining whether a virtual reference has been added to the reference queue. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is reclaimed.

1. Release strong references

Generally speaking, when we declare an object variable, we don't care after using it, thinking that the garbage collector will help us reclaim the memory space that these objects point to. In fact, if the memory space of the object is still in the referenced state, the garbage collector will never reclaim its memory space, and only when the memory space is not referenced by any object will the garbage collector collect it.

So after we finish using the object, we can leave the object empty so that my garbage collector gc will free up the memory space allocated for the object at the appropriate time.

Object obj = new Object (); obj = null

Of course, if you set it to * * to confirm that you no longer need to use the object, you cannot do so if you need to use it at any time

2. Use soft references

All soft references are cleared before jvm reports running out of memory, so that gc can collect the memory space released by many soft references, thus solving the problem of memory tightness and avoiding memory overflows. when it is reclaimed depends on gc's algorithm and the amount of memory available at gc runtime.

We can use SoftReference to encapsulate strongly referenced objects

String str = "zhuwentao"; / / strong reference SoftReference strSoft = new SoftReference (str); / / encapsulate strong reference with soft reference

3. Use weak references

Gc collects weakly referenced objects in the same way as soft references, except that gc does not decide whether to recycle weakly referenced objects based on memory conditions.

String str = "zhuwentao"; / / strong reference WeakReference strWeak = new WeakReference (str); / / encapsulate strong reference with weak reference

If you want to be able to get information about an object at any time, but don't want to affect the object's garbage collection, you should use WeakReference to remember the object instead of using normal Reference.

Image processing.

Most OOM occurs in image loading, and when we load large images, we need to pay special attention to avoid the occurrence of OOM.

When dealing with large pictures, no matter how big your phone's memory is, memory overflow problems may occur if the pictures are not processed.

Because the Android system allocates a certain amount of memory for each application, it does not allocate the entire system memory to the application, so no matter how much memory your phone has, the memory it can use for each App is limited.

This is very different from the PC side, the PC side can also request to use virtual memory if there is not enough memory, but the Android system does not have this mechanism.

1. Compress the picture in memory

When loading a large picture, you need to compress the picture, and use the proportional compression method to process the picture directly in memory.

Options options = new BitmapFactory.Options (); options.inSampleSize = 5; / / 1/5 of the original image, set to 2 to 1/2 BitmapFactory.decodeFile (myImage.getAbsolutePath (), options)

In doing so, it is important to note that the picture quality will become worse, the higher the inSampleSize setting, the worse the picture quality, and different phone manufacturers may have different scaling ratios.

2. Recycle the memory occupied by the picture after using the picture

Because the outer layer of Android uses java while the bottom layer uses the memory space allocated by C language for picture objects in the inner layer.

So although our outer layer seems to be released, the inner layer is not necessarily completely freed. We release the inner memory space after using the image.

If (! bitmapObject.isRecyled ()) {/ / Bitmap object is not recycled bitmapObject.recycle (); / / release System.gc (); / / remind the system to reclaim in time}

3. Reduce the color quality of the picture to be displayed

There are four image color modes in Bitmap in Android:

ALPHA_8: each pixel needs to occupy the 1byte in memory

RGB_565: each pixel needs to occupy the 2byte in memory

ARGB_4444: each pixel needs to occupy the 2byte in memory

ARGB_8888: each pixel needs to occupy the 4byte in memory

When we create Bitmap, the default color mode is ARGB_8888, which is of quality, and of course takes up a lot of memory.

ARGB_4444 only takes up 2byte per pixel, so using ARGB_4444 mode can also reduce the amount of memory used by images.

BitmapFactory.Options options = new BitmapFactory.Options (); options.inPreferredConfig = Bitmap.Config.ARGB_4444; Bitmap btimapObject = BitmapFactory.decodeFile (myImage.getAbsolutePath (), o

In fact, after most pictures are set to ARGB_4444 mode, there is no difference with ARGB_8888 mode in the display, but in pictures with gradient effect, the gradient may show the effect of color bars.

This method of reducing color quality is not as effective as method 1 in reducing memory.

4. Do not load the picture into memory when querying the picture information.

Sometimes we get a picture, perhaps just to get some information about the picture, such as width, height and other information, do not need to be displayed on the interface, at this time we do not have to load the picture into memory.

BitmapFactory.Options options = new BitmapFactory.Options (); options.inJustDecodeBounds = true; / / do not load the picture into memory Bitmap btimapObject = BitmapFactory.decodeFile (myImage.getAbsolutePath (), options)

The inJustDecodeBounds property, if the value is true, does not return the actual Bitmap object and does not allocate memory space, but allows us to query basic information such as picture width, height, size, and so on.

(get original width and height: options.outWidth,options.outHeight)

VMRuntime

VMRuntime is a class provided in Android SDK.

It is only useful before Android2.3, but SDK after 2.3is not supported, so this VMRuntime is not universal.

Just give me a brief introduction here.

1. Optimize the heap memory allocation of Dalvik virtual machines

The setTargetHeapUtilization method provided by the VMRuntime class can enhance the processing efficiency of program heap memory.

Private final static float TARGET_HEAP_UTILIZATION = 0.75f; VMRuntime.getRuntime () .setTargetHeapUtilization (TARGET_HEAP_UTILIZATION)

2. Custom heap memory size

Forces the amount of memory allocated by Android to the current App, using the VMRuntime setting to apply the minimum heap memory.

/ / set the minimum heap memory to 6MB size private final static int HEAP_SIZE = 6 * 1024 * 1024; VMRuntime.getRuntime () .setMinimumHeapSize (HEAP_SIZE)

LargeHeap

Let the Dalvik virtual machine allocate more memory to the App. This method can win more memory space for our App, thus relieving the pressure of insufficient memory.

You can use the ActivityManager.getMemoryClass () method in the program to obtain the size of App memory under normal use, and use ActivityManager.getLargeMemoryClass () to obtain the memory size of * * when largeHeap is turned on.

1. Usage

This method is very simple to use, as long as you add "android:largeHeap=" true "" to the node attributes in the AndroidManifest.xml file

2. Pay attention

The memory that Dalvik adds to our App is probably acquired by killing other background processes, which is immoral for a developer.

We should not rely on fighting for the memory of OOM to solve the problem of OOM. We should write reasonable code to avoid the problem as much as possible.

Thank you for reading, the above is the content of "what is the method of avoiding memory overflow in Android". After the study of this article, I believe you have a deeper understanding of what the method of avoiding memory overflow in Android is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report