Which you'll find resources to sell 115

[Ten Wei: PPS33A integrity management] [] [] [wide variety of continually updated] [randomly selected] [Android] quality and security for each application allocates memory when using flexible distribution, that is, the beginning of the application does not give allocate a lot of memory, but to each process assigned a "good enough" memory size, the size of this value is based on the actual physical memory size of each device to decide.

 

With the application of operation and use, Android application will allocate some additional memory size. However, the size distribution is limited, the system can not assign infinite amount of memory for each application.

 

In short, Android system requires utmost to make the process more alive in memory, in order to ensure that reduce application startup time when the user opens the application again, improve the user experience.

 

Details about the Android system memory management mechanism, I recommend reading the next two articles: talk about Android's memory management, garbage collection mechanism for the Android operating system.

 

Avoid memory overflow

Memory overflow (Out Of Memory referred OOM), simply put out of memory refers to the program is running, the application memory is greater than the system can provide memory, making it impossible to apply sufficient memory, so memory overflow occurs.

 

Reduced memory footprint target

Avoid OOM first step is to minimize the newly allocated objects out of the memory size, try using more lightweight objects.

 

Using more lightweight data structure

For example, we may consider using ArrayMap / SparseArray HashMap rather than traditional data structures.

 

Ordinary HashMap implementations consume more memory, because it requires an additional instance of the object to record Mapping operation. Further, SparseArray more efficient in that they avoid the value of autobox key autoboxing, and avoids the packing box solution.

 

For more ArrayMap discussion / SparseArray, refer to the previous performance optimization - computing performance optimized content.

 

Correct use enumerated types

Enumerated types (Enums), it is a feature of the Java language. But the official Android is strongly recommended not to use Android application to Enums in which, because of enumerated type after compilation will generate a lot of inner classes, on mobile devices is obviously more precious memory will be occupied memory. For implementation details enumeration can see the implementation of the principles of Java enum type this article.

 

So understanding the implementation of the principles enumerated type can be found, it is not impossible to use enumerated types in the Android program, but recommended. Rational use of enumerated types can do some very elegant operation, such as a singleton.

 

public enum  EnumSingleton {

    INSTANCE;

}

1

2

3

We bytecode decompilation can see:

 

public final class EnumSingleton extends Enum<EnumSingleton> {

  public static final EnumSingleton INSTANCE;

  public static EnumSingleton[] values();

  public static EnumSingleton valueOf(String s);

  static {};

}

1

2

3

4

5

6

From the decompiled code, INSTANCE is declared as static, the class loading process, the virtual guarantee * <clinit> () * method is properly locked a class in a multi-threaded environment, synchronization. Therefore, the enumeration is achieved when instantiating thread safe.

 

Java Virtual Machine specification requirements, enumeration each enumeration type very defined in the JVM is unique, so the serialization and de-serialization of enumerated types, Java made a special provision.

 

In Java serialization only when the name attribute is an enumeration object to the output results, deserialized when it is based on the names to look for objects through an enumeration of java.lang.Enum valueOf method. Meanwhile, the compiler does not allow any customization of this serialization mechanism, thus disabling the writeObject, readObject, readObjectNoData, writeReplace readResolve and other methods.

 

Deserialization plain Java class, it will be to initialize the object by calling the default constructor class reflection. Therefore, even if a single embodiment constructor is private, it will be reflected to destroy. Since the object after re new deserialization out, so this single embodiment destroyed.

 

However, the enumeration of deserialization is not achieved by reflection. Therefore, a single case of damage due to the problems caused by anti-serialization will not happen.

 

Interested can see the answer on stackoverflow What is an efficient way to implement a singleton pattern in Java?

 

Bitmap object is to reduce the memory footprint

Bitmap is very easy to consume a big fat memory, memory footprint about the size of Bitmap details, please refer to Android Pit files: Bitmap exactly how much of your memory? , Created out of the Bitmap is reduced memory footprint is very important, in general, have the following two measures:

 

scaling ratio

Before the picture into memory, we need to calculate an appropriate scaling, to avoid unnecessary loading the big image.

 

Decoding format

Select ALPHA_8 / ARGB_4444 / ARGB_8888 / RBG_565, there is a big difference.

 

Mode Description occupied bytes

1B consists of 8 bits ALPHA_8Alpha

ARGB_44444 composed of 4-bit 16, each of the four color elements station 2B

ARGB_88884 8 is composed of 32 bits per color component stations 8 (default) 4B

RGB_565R to 5, G is 6, B is a total of five 16-bit, no Alpha2B

A smaller picture

In the design of the resources given to the picture, we need to pay special attention to the existence of this image can be compressed space, whether you can use a smaller picture.

 

Try to use a smaller picture not only can reduce memory usage, but also a large number of InflationException avoided. Say you have a great picture is a direct reference to an XML file, most likely will InflationException because of insufficient memory occurs when the initialization of view, the root cause of the problem is actually happening OOM.

 

JPG、PNG、WebP

These three recommendations do not understand the look of the picture format JPG and PNG What is the difference? , WebP support the status quo principle and Android introduce these two articles.

 

Picture compression

Image compression is recommended facie knowledge Tencent Android music technology team in the picture compression analysis (on), Android in the picture compression analysis (next) two articles.

 

Understand the compression of images related knowledge, we can write their own algorithms to achieve picture compression, you can also use the excellent open-source libraries, such as: Luban.

 

Repeat use of memory objects

In addition to reducing the memory occupied by objects, rational reuse memory object is also a good way to avoid memory overflow.

 

Reuse most objects, the final implementation of the program is the use of object pool technology, either inside the program to create explicit in the preparation of the code object pooling, and then deal with the implementation logic reuse, or is using the system framework some reuse existing properties to achieve the object of reducing repeat created, thereby reducing the memory allocation and recovery.

 

LruCache

A caching algorithms most commonly used in Android is LRU (Least Recently Use), is exceeded when the cache capacity on the priority list out of the data in the least recently used.

 

LruCache bitmapCache = new LruCache<String, Bitmap>();

// set the cache size based on memory space

ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

int availMemInBytes = am.getMemoryClass() * 1024 *1024;

LruCache bitmapCache = new LruCache<String, Bitmap>(availMemInBytes/8);

1

2

3

4

5

Use LruCache can cache Bitmap object, just the same LruCache memory object is valid, if we want pictures, video and other large files cache can use JakeWharton God open source DiskLruCache on disk.

 

Use Glide

Glide is a fast and efficient Android image loading library, focus on a smooth scrolling. Glide provides a user-friendly API, high performance, scalable picture decoding pipeline (decode pipeline), as well as automatic resource pooling.

 

Glide also recommended the Google open source project, see: Glide.

 

Multiplexing system comes with resources

Android system itself is built a lot of resources (for example: string, colors, images, animation, to style, simple layout, etc.), these resources can be directly referenced in the application.

 

Doing so not only can reduce their load application, reduce the size of your APK, you can also reduce the memory overhead to a certain extent, better reusability. But it is necessary to pay attention to differences between versions of the Android system, the situation there is a big difference between those different versions of the system performance does not meet the requirements, or need built into the application itself.

 

Multiplexing ConvertView

Number of views which duplicate subassembly of ConvertView multiplexing appears ListView, GridView like.

 

onLowMemory()

OnLowMemory is provided API Android, out of memory in the system, all the background programs (priority process Background and not to the process running in the background) have been killed, the system will call OnLowMemory.

 

Callback system provides are: Application, Activity, Fragementice, Service, ContentProvider.

 

onTrimMemory()

OnTrimMemory API is provided after Android 4.0, depending on the system memory to the callback status.

 

Callback system provides are: Application, Activity, Fragementice, Service, ContentProvider.

 

OnTrimMemory parameter is different from an int value represents the memory state.

 

App when running in the foreground, level of the function (from low to high) are:

 

TRIM_MEMORY_RUNNING_MODERATE

The system starts running App is running in low memory state, it will not be killed.

 

TRIM_MEMORY_RUNNING_LOW

The system is running in a more low-memory state, App running, will not be killed App can clean up some resources to ensure smooth system.

 

TRIM_MEMORY_RUNNING_CRITICAL

The system is running at a relatively low memory state, App is running, and the system does not think we can kill this App, the system began to kill background processes. At this point, App should go to free up some important resources.

 

When the App is running in the background, level status are:

 

TRIM_MEMORY_UI_HIDDEN:

App is not visible UI, App can clean larger resource use UI.

 

When the App goes into the background LRU List:

 

TRIM_MEMORY_BACKGROUND

System running in low memory, App process begins near the LRU List, App despite the risk of not being killed, but the system may have is to kill background processes. App should be easy to clean up some resources to recover.

 

TRIM_MEMORY_MODERATE

System running in low memory, App attachment process in the middle of the LRU List, App at this time may have been killed.

 

TRIM_MEMORY_COMPLETE

System running in low memory, killed one of the App is first choice, App App should be promptly cleaned up to restore the state to the front, all the resources unimportant.

 

In addition, a more App occupy memory, the system will clean up the background LRU List, the more likely priority is to clean up. So, we have to be careful to use memory usage.

 

Avoid creating objects inside onDraw execution method

OnDraw similar methods frequently called, must be taken to avoid the need to do the operation here to create an object, because he will be a rapid increase in the use of memory, and can easily lead to frequent GC, or even shake the memory.

 

Serialization

Android implemented serialization in general and with Serializable Parcelable two ways.

 

The maximum difference between the two lies in the different storage media, Serializable using I / O read and write stored on the hard disk, and is read directly Parcelable in memory. Obviously, the write speed is typically greater than IO read memory, the data is transmitted in Android preference Parcelable.

Serializable will use reflection, serialization and deserialization process requires a lot of I / O operations, to achieve a Parcelable own marshaling and unblocking (marshalled & unmarshalled) operations need not be reflective, the data stored in the memory Native efficiency much faster.

 

Parcelable performance better than Serializable, small in terms of memory overhead, it is recommended to use Parcelable (such as data transmission between Activity) at the time of data transfer between memory.

 

The Serializable data persistence can be easily stored, so the need to save or select Serializable network to transmit data, because different versions of Android Parcelable may be different, it is not recommended Parcelable for data persistence.

 

StringBuilder

In some cases, the code will be required to operate a large number of strings together, it is necessary to consider the use of this time instead of frequent StringBuilder +.

 

Avoid memory leaks

Memory leaks (Memory Leak) means the program is running in memory to allocate temporary variables, exhausted after but not be recovered GC, always occupy the memory, neither can be used can not be allocated to other programs, so he creates a memory leak.

 

Memory leak sometimes serious and difficult to detect, so developers do not know there is a memory leak, but sometimes very serious, and even prompt you OOM.

 

Context leak

In Android development, memory leak problem is most likely to lead to Context. For example, Activity of Context, contains a large amount of memory references, once leaked Context, it also means that all objects leakage points.

 

Activity leak caused by a common cause:

 

Static references Activity

Activity static variables defined in the class, the Activity currently running instance assigned to the static variables. If the static variable is not empty at the end of the Activity life cycle, it causes a memory leak.

 

Because static variable throughout the life cycle of the application, they were leaked Activity will always exist in the application process will not be garbage collected.

 

static Activity activity; // this code is to be avoided

1

Stored in a single embodiment Activity

In the single-mode embodiment, if Activity often used, then stored in a memory Activity example is very useful.

 

However, due to the life cycle of a single case of the life cycle of the application, it will force the extension of the life cycle of Activity, which is quite dangerous and unnecessary, and in any case can not save objects similar Activity in a single case.

 

public class Singleton {

  private static Singleton instance;

  private Context mContext;

  private Singleton(Context context){

    this.mContext = context;

  }

 

  public static Singleton getInstance(Context context){

    if (instance == null){

      synchronized (Singleton.class){

        if (instance == null){

          instance = new Singleton(context);

        }

      }

    }

    return instance;

  }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Activity in the incoming call when the Singleton getInstance () method. So when the instance is not released, the Activity will always exist, and therefore cause a memory leak.

 

Consider using instead Activity Context Application Context

For most non-essential use of Activity Context (Dialog of Context must be Activity Context), we can consider using the Application Context instead of Context Activity, Activity avoid inadvertently leaked.

 

Inner Classes

Advantages inner classes can improve the readability and encapsulation, and can be accessed outside the class, unfortunately, lead to a memory leak reason is that inner classes held outside of class instances of strong references (for example, holds Activity within the class of objects ).

 

Solution:

 

The inner class becomes static inner classes;

If there is strong reference Activity of property, the property reference to weak references;

In the case of business permitting, when the Activity execution onDestory, the end of these time-consuming tasks.

Avoid using asynchronous callbacks

Time asynchronous callback to be executed uncertainty is likely to occur after the Activity has been destroyed, not only easily lead to crash, it is still prone to memory leaks.

 

Note the temporary Bitmap object timely recovery

Although in most cases, we will increase Bitmap caching mechanism, but at some point, part of the Bitmap is the need for timely recovery.

 

For example: a relatively large temporary Bitmap object is created, after transform new Bitmap object, should be recovered as soon as possible the original Bitmap, this can free up space occupied by the original Bitmap faster.

 

Requiring special attention is the Bitmap class which provides the createBitmap () method, this function returns the Bitmap possible and source bitmap is the same, at the time of recovery, we require special inspection referenced source bitmap and return bitmap is the same, only without under such circumstances, to be able to perform recycle method of source bitmap.

 

Note that listeners log out

There are many needs to register and unregister the listener inside the Android application, we need to ensure that at the right time timely unregister those listeners. To manually add the listener, need to remember to remove this listener.

 

Note whether objects close the Cursor

In the process, we often operate query the database, but there is often the case after the careless use of Cursor did not close. Cursor these leaks, the repeated occurrence of memory management, then would have a huge negative impact, we need to remember to close the Cursor object.

 

Note that the object cache container leak

Sometimes, in order to improve the reusability of objects put some objects into the cache container, but if these objects are not promptly removed from the container, also may lead to memory leaks.

 

For example: For System 2.3, if the drawable added to the cache container, because the strong drawable and View application, the activity can easily lead to leaks. From 4.0, this problem does not exist. To solve this problem, we need to make special package cache drawable on the 2.3 system, processing reference unbundling of the problem, to avoid leakage.

 

Note WebView leak

Android WebView in the presence of a great compatibility issues, just different versions of the Android system a big difference to WebView, another different vendors shipped ROM inside WebView there are also significant differences. More serious is a memory leak standard WebView issues, see here WebView causes memory leak - leaks the parent Activity.

 

It is usually cure this problem is to open another process for the WebView, communicate through AIDL with the main process, the process can be destroyed where WebView need to choose the right time according to the business, so as to achieve a complete release memory.

 

Lint Tool

Lint is scanning the code analysis tools provided by Android Studio, it can help us find the code structure / quality issues, while offering some solutions, and this process does not require us handwriting test.

 

Lint each problem has found a description and rating (tested and found very similar bug), we can easily locate the problem, at the same time be resolved in accordance with severity.

 

Click Analyze> Inspect Code to open the Lint tool.

 

Lint

 

For detailed description can view the Android development documentation - Use Lint improve your code, Android Performance Optimization: Using Lint optimized code, remove excess resources, these two articles, the use of relatively simple, a lot of resources online introduction, there is no longer described in detail.

Guess you like

Origin www.cnblogs.com/jenixbsk/p/12161015.html