This manual is intended for developers who have at least a beginner's experience to access or review relevant knowledge, and novice users may not be able to read it.
1, Java code Optimization 1.1 Android How to execute code
dvm:.java->.class->.dex->.apk
- To optimize the Fibonacci sequence:
The recursive formula for the Fibonacci sequence is f (n) =f (n-1) +f (n-2), with the characteristic equation: x2=x+1, the equation to be (1+sqrt (5))/2, (1-SQRT (5))/2. So f (n) =ax1n+bx2n, bring in F (0) =0,f (1) = 1 a=sqrt (5)/5,B=-SQRT (5)/5. Then f (n) is calculated.
Use this class to solve the overflow problem.
The Fibonacci sequence has the following properties:
(fn fn-1) = (fn-1 fn-2) *a, can be derived a= (1 1;1 0)
Recursion available: (fn fn-1) = (fn-1 fn-2) *a= (fn-2 fn-3) *a2=...= (F1 F0) *an-1
-
Cached results:
Use HashMap to act as a cache and use Sparsearray more efficiently when the key is an integer.
-
LruCache:
Suitable for caching images, 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 cache value reaches a predetermined value.
-
private LruCache<integer, string=""> mJsonCache; /** * 缓存图片信息 */ private LruCache<integer, bitmap=""> mBitmapCache; public Util() { mJsonCache = new LruCache<integer, string="">(1 * 1024 * 1024); mBitmapCache = new LruCache<integer, bitmap="">(2 * 1024 * 1024); }
-
Data:
Android has added some of its own implementations to these data structures, typically to improve performance, Lrucache\sparsearray\sparsebooleanarray\sparseintarray\pair
There are also arrays and collections classes. For example, use Arrays.sort to sort the array.
-
Responsiveness: Configure android:configchanges Properties When you are familiar with life cycles, such as device orientation changes
- Deferred initialization: For example, android.view.ViewStub can be used to postpone initialization. Because memory allocation takes time, it is also a good choice to wait until the object is really needed.
- Stricmode: The main thread is not used to access time-consuming operations such as the network.
- SQLite statement: Speed up the creation of the SQL statement string to be executed, in which case using the + operator to concatenate strings is not the most efficient method, while using the StringBuilder object, or calling String.Format, can improve performance.
- Transactions: One-time transaction resolution. You can use Sqliteopenhelper instead of manually creating a database.
- Query: Create cursor only get first column
2. NDK
Written primarily by C + +, is the native development kit for Android.
1. Create a local method:
public native String encode(String text, int length);public native String decode(String text, int length);}
2. Implement the JNI adhesive layer:
Automatically generated using the JDK's Javah tool.
- Create a JNI folder under the project root directory
- Create a C file in the Jni file
-
In Java code, create a local method HELLOFROMC
public native String helloFromC();
-
In JNI, define the function implementation of this method, the function name must be
jstring Java_com_zhilinghui_helloworld1_MainActivity_helloFromC(JNIEnv* env, jobject obj)
-
Returns a string that defines a string in C
char* cstr = "hello from c";
-
Converts a C string into a Java string
jstring jstr = (*env)->NewStringUTF(env, cstr);return jstr;
- Create a android.mk file in JNI
- Add in C file
Wirelessly how to use C + + code (summary)
The front can be said a bit messy, here is a brief summary:
- Step One:
The interface for defining a C method in Java is equivalent to the implementation of an interface interface defined in Java code that is implemented by the C language.
Public native String hello ();
-
Step Two:
Implementing C code
Method names are strictly in accordance with the specification of JNI
-
Step Three:
Creating android.mk tells the compiler how to package C code into a library of functions
Local_path: = $ (call My-dir)
-
Step Four:
Package C code into a library using the installation environment to use Ndk-build packaging in the appropriate directory
-
Step Five:
Introduction of library functions in Java code
- Step Six:
How to use
3. NDK Advanced
Assembly optimization: The features of the GCC compiler are built into the Android NDK.
Be sure to decompile the target files and libraries using the correct version of Objdump.
Arm mode and thumb mode.
- Color conversion: The most common operation in a graphics program is to convert colors from one format to another, ARGB8888 and RGB565.
- RAM Instructions
Tips for improving performance
- inline function: The substitution call is implemented directly at the call. Add the "inline" keyword before the function definition.
- Cyclic expansion: expansion can actively dispatch (or pipelining) loops to mask some delays. This is useful if you have enough free registers to keep the variables active because you expose critical paths by expanding the dependency chain.
- Memory Pre-read: 1. The--builtin_prefetch () of GCC, 2, the use of PLD and the PLDW instruction in the arm assembly code, and the PLI instructions are also available.
- Replace LDR/STD with ldm/stm: Loading multiple registers with a single instruction is faster than loading registers with multiple LDR instructions.
4. Efficient Use of memory
The Java char is 16 bits (UTF-16), the Long of Java is 64 bits, and the long of C is 32 bits, and long long is 64 bits.
Accessing Memory:
Methods to reduce the chance of data cache read misses: 1, when there is a large amount of data stored in the array, use the smallest possible data type, 2, select sequential access instead of random access, to maximize the reuse of the data already in the cache.
Garbage Collection: Memory leaks
When an object is no longer referenced, its memory is recycled and oom occurs when the object reference that is disposed of is still present.
For example: when the screen rotates. The heap and allocation tracker in DDMS can be traced in eclipse.
You can also use the Stricmode class to detect potential memory leaks.
Reference
-
Strong references: Most of the programs are such references. is the "normal" reference.
– BigIntegerbi=BigInteger.valueOf(n);//强引用
Integer i=new Integer(n);//强引用
The I=null;//integer object becomes recyclable garbage.
-
Soft, weak, virtual references:
Soft and accessible objects, the garbage collector decides to reclaim the old collection itself. The weak and accessible objects are basically recycled. Virtual references, which are rarely used, can be used to register reference queues.
- Garbage collection
It may be triggered at an indefinite time, with little control over its occurrence, such as when the heap is full of memory allocations and the new object is being allocated for memory collection.
Api
- Activitymanager getmemoryinfo (), Getmemoryclass (), Getlargememoryclass ();
- Debug Dumhprofdata (), Getmemoryinfo, Getnativeheapallocatedsize (), Getnativeheapsize ().
-
ActivityManager am=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);ActivityManager.MemoryInfo memInfo=new ActivityManager.MemoryInfo();am.gettMemoryInfo(memInfo);
5. Multithreading and synchronization threads
The thread object. The run () method can be replicated, and the Runnable object is passed to the thread constructor. Remember to call Start ().
The thread priority, typically 1-10 (highest), is 5 by default. Linux is prioritized from 20 to 19 (lowest).
Asynctask
Asynctask start task stack execution of input parameters, background task execution percentage, background task execution return IUD result, anonymous class.
For example: Refresh foreground progress bar when downloading files in background.
Handler and Looper
They are the cornerstone of multithreaded application-to-thread communication.
Handler
- Handler: Handler, responsible for sending and processing the message. When using handler, you need to implement the Handlemessage (Message msg) method to process a specific message, such as updating the UI.
Handler is created in the run () method because it needs to be bound to the specified looper, which looper is created by calling Looper.prepare (0) in the run () method. Call GetHandler () to return null before the thread is generated.
Looper
A thread that has a message loop.
- Looper: The message pump continuously extracts message execution from the MessageQueue. Therefore, a MessageQueue needs a looper.
-
Message: Messages that contain the message ID, the message Processing object, and the processed data are queued by MessageQueue and processed by handler.
-
MessageQueue: Message Queuing, which holds messages sent by handler and executes according to FIFO rules. Of course, storing a message is not a meaningful preservation, but rather a concatenation of the message in the form of a linked list, waiting for the looper to be extracted.
-
Thread: threads, responsible for dispatching the entire message loop, that is, the execution site of the message loop
Activity life cycle
7 Life Cycles
Calling Asynctask.cancel () triggers oncancelled () instead of Onposeexecute () after Doinbackground () is returned.
6. Performance Evaluation and analysis
The TraceView in Ddms
-
View the execution time of the tracking code, analyze which are time-consuming operations, and can be used to track calls to methods, especially the method call relationships of the Android framework layer
-
TraceView lists all the methods that are heard, and of course the time-consuming of many methods of Android, how do you find out what you care about in so many ways? Can be found through the bottom of the TraceView find, usually the Android app is a package name, you can first for some of the concerns of the column after sorting, through the package name to find out, which saves yourself to filter out the time of the application of their own methods.
7. Extend Battery life
The general screen and WiFi are very power hungry.
Measuring battery usage
You can retrieve a fixed intent by retrieving it. Get the battery's current charge when the app starts, run for a while, and get the battery power again when you exit. However, this value is not accurate because there are other applications running.
Disable broadcast Receivers
The broadcast receiver is enabled only if needed.
- Because Batterymanager broadcasts a sticky intent entity, which means you don't have to register a broadcast receiver to get your program to accept this broadcast, you can just call Registerreceiver this method, Pass NULL on the parameter where you want to add the broadcast receiver, and of course you can create a new broadcast receiver and pass in when you register the broadcast receiver.
Internet
The final solution to the problem, at-and-T with the staff from the University of Michigan colleagues conducted a comprehensive survey of end-to-end data transmission paths, and ultimately found to be the root cause of the complex interaction between devices and cellular networks, interacting, is difficult to see, gives a layered network architecture, Intentionally hides low-level protocol developers working at the application layer.
More articles can be consulted: http://www.research.att.com/editions/201106_home.html
Position
Use
WakeLock
For example, when a user watches a video or movie, the CPU needs to decode the video while keeping the screen open for the user to watch.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); WakeLock sCpuWakeLock = pm.newWakeLock( PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,"okTag"); if (sCpuWakeLock!= null) { sCpuWakeLock.release(); sCpuWakeLock = null; }
- Partial_wake_lock: Keep the CPU running, and the screen and keyboard lights may be off.
-
Screen_dim_wake_lock: Keep the CPU running, allow the screen to be displayed but may be gray, allow to turn off the keyboard light
-
Screen_bright_wake_lock: Keep the CPU running, keep the screen highlighted, allow the keyboard light to turn off
-
Full_wake_lock: Keep the CPU running, keep the screen highlighted, and the keyboard lights remain bright
Acquire_causes_wakeup: Does not wake the device, force the screen to be highlighted immediately, the keyboard light is turned on. With one exception, if a notification pops up, the device will wake up.
- On_after_release:wakelock is released, maintain the brightness of the screen for a short period of time, reduce the flicker when the WakeLock cycle
If you apply for partial wakelock, the system does not enter sleep even if you press the power key, such as music playback if you apply for other wakelocks, press the Power key, the system will still go to sleep
However, if you do not understand the intentions of the Android designer to misuse the wake Lock API, in order to its own program in the background of the normal operation and long time to prevent the AP into hibernation, will become a standby battery killer.
Remind
Alarmmanage has a alarmmanagerservice, the service program is mainly to maintain the app registered alarm, and always monitor the alarm device, once there is a alarm trigger, or alarm event occurred, Alarmmanagerservice will traverse the alarm list, find the appropriate registration alarm, and issue a broadcast.
Alarm Manager will maintain a wake lock on the CPU. This ensures that when the phone sleeps, it can also handle alarm broadcasts. Once alarm receiver's onreceive () method is executed, Wake Lock is released quickly. If a service is turned on in receiver, it is possible that the service has not been started and Wake Lock has been released. So this is the time to implement a separate wake lock policy.
There are 4 types of alarm:
1) rtc_wakeup
At the specified moment (when setting the alarm), wake the device to trigger the intent.
2) RTC
Triggers the intent at an explicit time, but does not wake the device.
3) Elapsed_realtime
After booting from the device, if the elapsed time reaches the total time, the intent is triggered, but the device is not awakened. The elapsed time includes any time the device sleeps. Note that the calculation point for the time lapse is since it was last started.
4) Elapsed_realtime_wakeup
When the total elapsed time is reached after the device is booted, the device is awakened and intent is triggered if necessary.
Sensors, graphics
There's no detailed introduction here.
8. Graphic Layout optimization
-
Call Setcontentview (). The XML layout of the time to reduce the number of objects created, you can use different layouts to achieve the same visual effect, eliminate unnecessary objects, or postpone the creation of objects.
-
Nested linear layouts deepen the layout hierarchy, resulting in slower layout and key handling. A relative layout is required when displaying 10 or more items.
-
Using <merge /> labels to merge layouts
-
<merge xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/add"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/delete"/>
* <include /> reuse layouts with labels
<include layout="@layout/titlebar"/>
Postpone loading
<ViewStub android:id="@+id/viewstub_demo_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dip" android:layout_marginRight="5dip" android:layout_marginTop="10dip" android:layout="@layout/viewstub_demo_text_layout"/>
Layout tools
In the Sdk->tools directory, there are hierarchyviewer and layoutopt to view and analyze layouts
OpenGL ES
OpenGL ES (abbreviated for the OpenGL for Embedded system) is a free two-and three-dimensional graphics library for embedded systems.
Any complex 2D or 3D figure is constructed from these three geometries. OpenGL ES provides two types of methods to draw a spatial geometry:
-
Public abstract void Gldrawarrays (int mode, int first, int count) is drawn using Vetexbuffer, and the order of vertices is specified in the order of VertexBuffer.
Public abstract void gldrawelements (int mode, int count, int type, Buffer indices), you can redefine the order of vertices, the order of vertices is defined by indices Buffer Availability
Mode list: Gl_points draws independent points, Gl_line_strip draws a segment, Gl_line_loop draws a closed segment (first connected), Gl_lines draws multiple segments, Gl_ Triangles Draw multiple triangles (22 nonadjacent), Gl_triangle_strip Draw multiple triangles (22 adjacent), Gl_triangle_fan draw multiple adjacent triangles at one point for vertices in addition to defining the coordinates, you can also specify a color , material, normal (for lighting processing), etc. Glenableclientstate and Gldisableclientstate can control the pipeline switch can have: gl_color_array (color), Gl_normal_array (normal), gl_texture_ Coord_array (material), Gl_vertex_array (vertex), gl_point_size_array_oes, etc. The corresponding methods for passing in colors, vertices, materials, and normals are as follows: glcolorpointer (int size,int type,int stride,buffer pointer) glvertexpointer (int size, int type, int stride, buffer pointer) gltexcoordpointer (int size, int type, int stride, Buffer pointer) glnormalpointer (int type, in T stride, buffer pointer) OpenGL ES internally holds graphics data in Buffer with color, DEPTH (depth information), and so on, before drawing graphics only generally need to empty color and DEPTH buffer.
-
The Universal Matrix Transformation directive describes some of the matrix operations and operations supported by the Android OpenGL es for the specified coordinate system (such as ViewModel, projection, or viewport). The matrix itself can support subtraction, and a 4x4 matrix of all 1 diagonals becomes the identity matrix of the unit matrices.
The instruction for setting the current matrix to the unit matrix is glloadidentity ().
The Matrix multiplication Instruction glmultmatrix* () allows you to specify any matrix multiplied by the current matrix.
Select the current matrix type Glmatrixmode (). OpenGL ES can run a coordinate system such as the specified Gl_projection,gl_modelview, and subsequent matrix operations will target the selected coordinates.
Sets the current matrix to any specified matrix glloadmatrix* ()
Save the current matrix in the stack and restore the stored matrix from the stack, you can use Glpushmatrix () and Glpopmatrix ()
Specific matrix transformations translate Gltranslatef (), rotate Glrotatef (), and scale Glscalef ()
Texture compression
Specific can be seen on the official website: http://developer.android.com/training/graphics/opengl/index.html
Coloring, scene complexity, blanking, rendering,
Frames are rendered only when the scene changes.
9, Renderscript
Renderscript is a low-level, high-performance programming language for 3D rendering and processing intensive computing (3D playback, and CPU-intensive computing). Android has consistently fared poorly in drawing performance and has improved since the introduction of the NDK, while the Renderscript has been released in Honeycomb after the framework, greatly increasing the execution and computing power of the Android native language.
Renderscript the first-pass compilation on the machine and then the last-pass compilation on the target device (Just-in-time compiling), resulting in more efficient native binary code. This means that any device that supports Renderscript can run your code. Don't care what architecture.
Currently, the code brought by Renderscript can only be run on the main processor, and it will automatically generate code that can take advantage of multiple cores if there are multiple cores on the device. As a result, the compiled program is optimized for the machine, which solves the device fragmentation, which means that developers no longer have to worry about the user's phone, tablet is not good enough, there is no GPU ... And so on, it's all given to Renderscript to worry about. No Gpu,renderscript write the program to the CPU to deal with (the compiler behind the technology is actually used LLVM).
Android Performance Optimization Brochure