Android Performance Optimization

Source: Internet
Author: User

Layout Optimization

How Android performance optimization avoids overdraw (Refer to)

( 1 ) Avoid Overdraw

Overdraw, excessive drawing can waste a lot of CPU,GPU resources, such as the system will draw the background of the activity by default, if the layout is redrawn overlapping background, then the default activity background is invalid over-drawn.

Over-rendering (Overdraw) is also a waste of CPU/GPU resources, and the system also provides a detection tool debug GPU overdraw to view the interface overdraw situation. The tool uses a different color to draw the screen to indicate where and to what extent overdraw occurs, where:
No color: Means no overdraw. Pixels are drawn only once.
Blue: means Overdraw 1 time times. The pixel was drawn two times. Large blue is still acceptable (if the whole window is blue, you can get rid of one layer).
Green: It means twice times the overdraw. The pixel was drawn three times. Medium-sized green areas are acceptable, but you should try to optimize and reduce them.
Light red: means Overdraw 3 times times. The pixel is drawn four times, and the small range is acceptable.
Dull red: it means 4 times times the overdraw. Pixels are plotted five or more times. This is wrong to fix them.


(2) Optimize the layout level

In Android, when the system is measuring, laying out, and drawing the view, it is done by traversing the view tree. If the height of a view is too high, it affects the speed of measurement, layout, and drawing, so the first way to optimize the layout is to reduce the height of the view tree, and Google in the API documentation also recommends that the view tree be no more than 10 levels high.
Avoid nesting too many useless layouts:
① reusing layout with <include> tags

In an application interface, in order to style the unity, many interfaces will have some common UI, for these common UI, if in each interface to copy a piece of such code, not only not conducive to later maintenance, but also increased the redundancy of the program. So you can use the <include> tag to define such a common UI.

Let's start by defining a simple common UI:

Code that will android: layout_width="0DP" and android: layout_height= the "0DP" is set to 0, which forces the developer to assign a value to the width when it is used, or the interface cannot be seen.

<?xml version= "1.0" encoding= "Utf-8"? ></span><span style= "font-family: Microsoft Ya hei;" ><textview  xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "0DP"    android:layout_height= "0DP"    android:textsize= "30DP"    android:gravity= "center"    Android:text = "This is a common UI"    />
<include layout= "@layout/common_ui"    android:layout_alignparentbottom= "true"    android:layout_width= " Match_parent "    android:layout_height=" Wrap_content "/>

If you need to overwrite android:layout_xxx properties in the <include> tag similar to the original layout, you must specify both the Android:layout_width and Android:layout_height properties in the label.
② using deferred load to implement view

<ViewStub> is a very lightweight component that is not only invisible, but also 0 in size.

First, create a layout that does not need to be displayed when initializing the load, but only in some cases, such as when viewing user information, where the user details are displayed only if a button is clicked. Let's write a simple layout:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout  xmlns:android= "http://schemas.android.com/apk/ Res/android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <textview        android:id= "@+id/tv"        android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:text= "not often use layout"        android:textsize= "30SP"/ ></LinearLayout>

Next, like using the <include> tag, the Layout property in <ViewStub> in the main layout references the above layouts.

<viewstub    android:id= "@+id/not_often_use"    android:layout_alignparentbottom= "true"    Android: Layout_width= "Match_parent"    android:layout_height= "wrap_content"    android:layout= "@layout/not_often_use "/>

How do I reload the displayed layout?

First, find the <ViewStub> component with the normal Findviewbyid () method, which is basically the same as the general component:

Mviewstub = (viewstub) Findviewbyid (r.id.not_often_use);

Next, there are two ways to re-display the view.

(1) VISIBLE

By calling Viewstub's Setvisibility () method to display the view, the code looks like this:

Mviewstub.setvisibility (view.visible);

(2) Inflate

This view is displayed by calling the inflate () method of Viewstub, which is the following code:

View Inflateview = Mviewstub.inflate ();

Both of these methods allow the viewstub to be re-unfolded, showing the referenced layout, and the only difference is that the inflate () method can return the referenced layout so that the corresponding control can be found through the View.findviewbyid () method, which is the following code:

View Inflateview = Mviewstub.inflate ();

TextView TextView = (TextView) Inflateview.findviewbyid (r.id.tv);

Textview.settext ("Hello");
What's the difference between Viewstub and view.gone?
What they have in common is that they are not initially displayed, but the former only renders the entire layout when it is displayed, while the latter is added to the layout tree when the layout tree is initialized, which is more efficient than the former layout.

③hierarchy Viewer: Tools to view the view tree

Memory Optimized

(1) Bitmap optimization

Use the appropriate resolution and size of the picture;

Timely recovery of memory: Starting with Android 3.0, bitmap is placed in the heap and its memory is managed by the GC, so it does not have to be released manually by calling the Bitmap.recycle () method;

Using picture caching: Designing memory caches and disk caches makes better use of bitmap.

(2) Code Optimization

Using the static method, it will increase the access speed by about 15% than the normal method;

Try not to use enumerations, less iterators;

To the cursor, Receiver, Sensor, file and other objects, we should pay great attention to their creation, recovery and registration, the solution registration;

Use Surfaceview to replace view for a large number of frequent drawing operations;

Try to use view caching instead of executing the Inflate method parsing view every time.

How to speed up activity

Android performance optimization accelerates application startup speed

The splash page for Android performance optimization should be designed like this

Starting mode

In general, there are two types of startup methods used in Android: Cold start and hot start.

1, cold start: When the application is launched, the background does not have the process of the app, then the system will re-create a new process assigned to the application, this startup is cold boot.

2, hot start: When the application started, the background already has the application of the process (example: Press the back key, the home button, although the app will exit, but the app's process is still left in the background, can go to the Task List to view), so in the case of existing processes, the launch will be from the existing process to launch the application This method is called hot start.

Characteristics

1, cold start: Cold start because the system re-creates a new process to assign it, the application class is created and initialized, and the Mainactivity class (including a series of measurements, layouts, drawings) is created and initialized, and finally displayed on the interface.

2, hot start: Hot start because it will start from the existing process, so the hot start will not go application this step, but directly go mainactivity (including a series of measurement, Layout, drawing), So the hot-start process only needs to create and initialize a mainactivity, without having to create and initialize the application, because an application is initialized from the creation of the new process to the destruction of the process, application only once.

Application-initiated processes

On Android, app launches are a process where there is no process: When you click on the app's startup icon, the Android system will zygote from the |za?g. t| fertilized eggs) in the process fork creates a new process to assign to the app, then creates and initializes the application class, creates the Mainactivity class, Loads properties such as Windowbackground in theme styles theme are set to Mainactivity and configure some properties on the activity level, inflate layout, when oncreate/onstart/ Onresume methods are finished after the last Contentview Measure/layout/draw display in the interface, so until then, the application of the first start is completed, this time we see the interface is said to be the first frame.

So, to summarize, the application start-up process is as follows:

The constructor method of the application-->attachbasecontext ()-->oncreate ()-->activity is constructed by-->oncreate () and the properties of the background in the configuration theme- ->onstart ()-->onresume () and the measurement layout is plotted on the interface.

how to deal with OOM problem

http://blog.csdn.net/wangqilin8888/article/details/7752528

Picture Oom processing Method:Android High-efficiency loading large map, multi-graph solution, effectively avoid program Oom

A. Compressing high-resolution images

B. Using the image caching technique, the core class is LRUCache

The main causes of Oom are two:

1. Due to errors in our procedures, the long-term maintenance of certain resources (such as the context) of the reference, resulting in memory leaks, resources caused by the failure to release.

2. Multiple objects that consume too much memory (such as bitmap) are saved, causing memory to exceed the limit.

Workaround for an oom that is too large for the picture:

1) Efficient loading of large images, using picture compression.

How can we compress a picture? This can be achieved by setting the value of insamplesize in bitmapfactory.options . For example, we have a picture of 2048*1536 pixels, set the value of Insamplesize to 4, you can compress this image into 512*384 pixels. Originally loading this image needs to occupy 13M of memory, compression will only need to occupy 0.75M (assuming that the image is the argb_8888 type, that is, each pixel occupies 4 bytes).

2) Using Image caching technology

Memory caching technology provides quick access to images that consume valuable memory from applications. The most core of these classes is LRUCache (this class is provided in the ANDROID-SUPPORT-V4 package). This class is ideal for caching images, and its main algorithm is to store recently used objects in linkedhashmap with strong references, and to remove the least recently used objects from memory before the cached value reaches a predetermined value.

How to handle memory overflow problems

1. Use more lightweight data structures
For example, we might consider using traditional data structures such as Arraymap/sparsearray instead of HashMap. The usual implementation of HashMap consumes more memory because it requires an additional instance object to record the mapping operation. In addition, Sparsearray is more efficient in that they avoid the automatic boxing of key and value (autoboxing), and avoid the boxed unpacking.

2. Avoid using enum in Android
The official Android training course mentions "Enums often require more than twice as much memory as static constants. You should strictly avoid use enums on Android. "For specific principles, please refer to" Android Performance Optimization Model (iii) ", so please avoid using the enumeration in Android.

3. Reduce memory consumption of bitmap objects
Bitmap is an extremely easy to consume memory of the big fat, to reduce the amount of memory created by the bitmap is the most important, usually has the following 2 measures:
insamplesize: Scaling, before loading the image into memory, we need to calculate an appropriate scale to avoid unnecessary large image loading.
decodeFormat: Decoding formats, select Argb_8888/rbg_565/argb_4444/alpha_8, there is a big difference

Reuse of 4.Bitmap objects
While reducing bitmap, it is also necessary to improve the reuse rate of bitmap objects, avoid frequent creation of bitmap objects, and reuse methods have the following 2 measures
LRUCache: "Least Recently used algorithms" is an extremely popular application in Android. A control that displays a large number of pictures, such as a ListView and a GridView, uses the LRU mechanism to cache processed bitmap, removing the least recently used data from the cache and preserving the most frequently used data.
Inbitmap Advanced Features : Use the advanced features of the inbitmap to increase the efficiency of Android systems in bitmap distribution and release execution. Using the Inbitmap property, you can tell the bitmap decoder to try to use an existing memory area, and the newly decoded bitmap will attempt to use the pixel data memory area occupied by bitmap in the heap. Instead of asking for memory to reapply an area to store bitmap. With this feature, even thousands of images will only need to occupy the memory size of the number of images that the screen can display.

5. Use smaller images
When it comes to giving a picture of a resource, we need to pay special attention to whether the image has a space that can be compressed, or if it can use a smaller image. Using smaller images as much as possible will not only reduce the use of memory, but also avoid a lot of inflationexception. Given that a large picture is directly referenced by an XML file, it is possible that the root cause of the problem is an oom when initializing the view inflationexception due to insufficient memory.

6.StringBuilder
In some cases, the code will need to use a large number of string concatenation operations, it is necessary to consider the use of StringBuilder to replace the frequent "+".

7. Avoid performing object creation in the OnDraw method
Similar to the frequent call method such as OnDraw, it is important to avoid doing the creation of objects here, because he will quickly increase the use of memory, but also easily caused by frequent GC, or even memory jitter.

8. Avoid memory leaks for objects

Https://drakeet.me/android-leaks

Common memory leaks for Android performance optimizations

· the static variables of the class hold big Data Objects
Static variables maintain references to large data objects for a long time, preventing garbage collection.

· static instances exist for non-static inner classes
A non-static inner class maintains a reference to an instance of an external class, and if an instance of a non-static inner class is static, the reference to the external class is maintained indirectly for a long time, preventing it from being recycled.

· resource object not closed
Resource objects such as (cursor,file files, etc.) often use some buffering, we should close them in time when we are not in use, so that their buffers can recover memory in time. Their buffering exists not only in the Java Virtual machine, but also outside the Java Virtual machine. If we simply set its reference to null without shutting them down, it often causes a memory leak.
workaround : For example, Sqlitecursor (in the destructor Finalize (), if we do not close it, it will close () itself closed), if we do not close it, the system will also close it when recycling it, but this is too inefficient. Therefore, when the resource object is not in use, it should call its close () function, turn it off, and then set to null. Be sure that our resource objects are closed when our program exits. The process of querying the database is often done, but there are often cases where the cursor is not closed after it has been used. If our query result set is relatively small, the memory consumption is not easy to find, only in a large number of times in the case of frequent operations to reproduce the memory problem, which will give future testing and troubleshooting difficulties and risks, remember after try catch, close the connection in the Finally method

Handler memory leaks (? )
Handler is present in the activity as an inner class, but the handler life cycle is not always the same as the activity life cycle, such as when the handler object has a message queued, it cannot be freed. In turn, the acitivity that should have been released cannot be recycled.

Workaround :

1. Declare handler as a static class so that the inner class no longer holds references to the external class and does not block the release of the activity

2. If an inner class really needs an object of an external class, you can declare a weak reference inside it to reference the outer class.

public class Mainactivity extends Activity {private Customhandler mhandler; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);        Mhandler = new Customhandler (this);    } Static class Customhandlerextends Handler {//internally declares a weak reference, referencing external class private weakreference<mainactivity > Activityweakreference;public MyHandler (myactivity activity) {            activityweakreference= new weakreference< Mainactivity > (activity);        } // ... ...       }}

3. When activity OnStop or OnDestroy, cancel the message and runnable of the handler object

@Overridepublic void OnDestroy () {//  If null, all callbacks and messages would be removed.    Mhandler.removecallbacksandmessages (null);}

· Some bad code habits
Some code does not cause memory leaks, but their resources are not reused, frequently requesting memory and destroying memory, consuming CPU resources while also causing memory jitter
Solution Solutions
If you need to request memory objects and dispose of objects frequently, consider using object pooling to increase the reuse of objects. For example, the ListView uses this idea to avoid frequent GC by reusing Converview

Android Performance Optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.