The fourth Chapter analysis System Information and security mechanism performance optimization of activity and activity call stack

Source: Internet
Author: User
Tags string tags

1.Activity life cycle
Understanding the life cycle is two graphs: the first picture is the life cycle diagram of the back-font

The second picture is a pyramid-shaped life cycle diagram.

Watch out.
(1) When returning from the stopped state to the foreground state, it is called first.onRestartmethod, and then call the subsequentonStartand other methods;
(2) Start another activity and finish, call the old activity's OnPause method, then call the new activity's Oncreate->onstart->onresume method, Then call the old activity's Onstop->ondestory method.
If you do not call finish then the old activity calls the Onpause->onsaveinstancestate->onstop method, and the Ondestory method is not called.
(3) If the application is in a stopped state for a long time and the system memory is extremely tense, the system will recycle the activity, and the system will callback before recyclingonSaveInstanceStatemethod to save the data bundle for your app. When the activity is recreated, the saved bundle data is passed to theonRestoreSaveInstanceStateMethods andonCreatemethod, this isonCreateMethod inBundle savedInstanceStateThe source of the parameter (the onrestoreinstancestate bundle parameter is also passed to the OnCreate method, and you can choose to do a data restore in the OnCreate method).
The Onsaveinstancestate method and the Onrestoreinstancestate method "not necessarily" are called in pairs.
Onsaveinstancestate's invocation follows an important principle that when your activity is destroyed by the system "without your permission", the onsaveinstancestate is called by the system, which is the responsibility of the system, Because it has to provide an opportunity for you to save your data.
Onrestoreinstancestate is invoked only if the activity is "indeed" destroyed by the system, and if it is simply stuck in the case where there is such a possibility, then the method will not be called, for example, when the activity is being displayed. The user presses the home button back to the main interface, then the user then returns to the activity, in which case the activity is generally not destroyed by the system for memory reasons, so the activity's Onrestoreinstancestate method will not be executed.

2.Activity Task Stack
In-app activity is managed by task stack tasks, where activity from a task can come from different applications, and the activity of the same application may not be in the same task. By default, the task stack manages activity based on the last-in-first-out principle of the stack, but activity can set some "privileges" to break the default rules, mainly through the attributes in the Androidmanifest file android:launchMode or through intent flag.

Standard: The default startup mode, in which a new activity is generated and the activity instance is pressed into the stack (regardless of whether the activity already exists in the task stack, it is in the new operation). For example: The order in the stack is a B c D, at this time D through intent jump to a, then the stack structure becomes a B c D A, click the return button to display the order is D C B A, in turn destroy.

Singletop: In singletop mode, if the current Activity D is at the top of the stack and then jumps to its own activity (that is, d) by intent, then a new D instance (walk Onnewintent ()) is not recreated. So the structure of the stack is still a B c D, if jump to B, then because B is not at the top of the stack, so a new B instance is created and pressed into the stack, the structure becomes a B c D b. Application example: Three push, point in is an activity.

Singletask: In Singletask mode, there can be only one instance of the task stack that corresponds to the activity. For example, the structure of the stack is now a B C D, at which point D jumps through intent to B (Walk Onnewintent ()), then the structure of the stack becomes: a B. C and D are destroyed by the stack eject, which means that instances above B are destroyed. If the system already exists an instance, the system will send the request to this instance, but at this time, the system will no longer invoke the OnCreate method that normally we process the request data, but call the Onnewintent method. Usually applied to the home page, the home must be at the bottom of the stack, but also at the bottom of the stack.

In singleinstance:singleinstance mode, the open activity is pushed into a new task stack. For example: The structure of the task Stack 1 is: a B c,c through intent jump to D (start mode of D is singleinstance), then a new task stack 2, the structure of the stack 1 is still a B C, and the structure of the stack 2 is D, when the screen shows D, After D jumps through intent to D, Stack 2 does not press into the new D, so the situation in the 2 stacks does not change. If d jump to C, then according to the C corresponding start mode in the stack 1 to do the corresponding operation, c if the standard, then D jump to C, the structure of the stack 1 is a B c C, at this time click the Back button, or C, the structure of the stack 1 into a B C, and will not go back to D.

3.Intent Flag Boot Mode
(1) Intent.FLAG_ACTIVITY_NEW_TASK : Use a new task to initiate activity, which is typically used to start the activity in the service because there is no activity stack in the service.
(2) Intent.FLAG_ACTIVITY_SINGLE_TOP : Similarandoid:launchMode="singleTop"
(3) Intent.FLAG_ACTIVITY_CLEAR_TOP : Similarandoid:launchMode="singleTask"
(4) Intent.FLAG_ACTIVITY_NO_HISTORY : When activity is started using this mode, the activity disappears and is not persisted in the task stack when the activity initiates other activity. For example a B, starting c,c in this mode in B and then starting D, the current task stack becomes a B d.

4. Empty the task stack
(1) clearTaskOnLaunch : Each time the activity is returned, all activity on top of the activity is cleared. This property allows the task to have only one activity at a time when it is initialized.
(2) finishOnTaskLaunch : Cleartaskonlaunch acts on other activity, while finishontasklaunch acts on himself. With this property, when you leave the task where the activity is located, the activity will be erased when the user returns. [I don't see how this works yet]
(3) alwaysRetainTaskState : If this property of activity is set to true, then the task of the activity will not accept any cleanup commands and keep the current task state, which is equivalent to giving the task a "death-free gold medal".

Android System Information and security mechanisms

1. Get System Information: android.os.Build andSystemProperty

Stringboard =Build.board;
StringBrand =Build.brand;
String Supported_abis =Build.supported_abis[0];
String device =Build.device;
String display =Build.display;
String fingerprint =Build.fingerprint;
String serial =build.serial;
String ID =Build.id;
String manufacturer =Build.manufacturer;
String model =Build.model;
String hardware =Build.hardware;
String Product =Build.product;
String tags =Build.tags;
String type =Build.type;
String codename =Build.VERSION.CODENAME;
String incremental =Build.VERSION.INCREMENTAL;
String release =Build.VERSION.RELEASE;
String Sdk_int ="" +Build.VERSION.SDK_INT;
String host =Build.host;
String user =Build.user;
String time ="" +Build.time;

String os_version = System.getproperty ("Os.version");
String os_name = System.getproperty ("Os.name");
String Os_arch = System.getproperty ("Os.arch");
String user_home = System.getproperty ("User.home");
String user_name = System.getproperty ("User.Name");
String User_dir = System.getproperty ("User.dir");
String User_timezone = System.getproperty ("User.timezone");
String Path_separator = System.getproperty ("Path.separator");
String Line_separator = System.getproperty ("Line.separator");
String File_separator = System.getproperty ("File.separator");
String Java_vendor_url = System.getproperty ("Java.vendor.url");
String Java_class_path = System.getproperty ("Java.class.path");
String java_class_version = System.getproperty ("java.class.version");
String Java_vendor = System.getproperty ("Java.vendor");
String java_version = System.getproperty ("java.version");
String java_home = System.getproperty ("Java_home");

2.APK Application Information: packagemanager and Activitymanager
in the Androidmanifest file, the activity information is The Activityinfo class is encapsulated, and the information for the nodes in the entire manifest file is encapsulated by the PackageInfo class, and also by the serviceinfo , applicationinfo , ResolveInfo , and so on.
where ResolveInfo encapsulates the upper-level information that contains information, so it can return information contained in Activityinfo, ServiceInfo, and so on. It is often used to help us find information that contains specific intent conditions, such as apps with sharing features and playback capabilities.

The

Packagemanager focuses on getting the app's package information, while Activitymanager focuses on getting information about the running application.
Packagemanager Common methods:
getpackagemanger , getapplicationinfo , Getapplicationicon , getinstalledapplications , getinstalledpackages , Queryintentactivities , queryintentservices , resolveactivity , Resolveservice et
Activitymanager encapsulates a number of objects, each of which holds important information.
activitymanager.memoryinfo : Information about system memory, such as Availmem (System available memory), Totalmem ( (total memory), etc.
debug.memoryinfo : This memoryinfo is mainly used for the statistical process of memory information;
Runningappproceeinfo : Run process information that stores information about the process, such as processName , pid , uid , and so on;
Runningserviceinfo : Information that runs the service, stores information about the service process, such as Activesince (the first time it is activated), and so on.

3.packages.xml files (located in /data/system the directory)
At the time of system initialization, Packagemanager's underlying implementation class Packagemanagerservice will scan some specific directories in the system and parse the APK file, Finally, the application information it obtains is saved to the Packages.xml file, which is also updated when the application in the system is installed, deleted, or upgraded.

4.Android security mechanism
Five lines of Defense:
(1) code security mechanism--code obfuscation Proguard
(2) Application Access authority mechanism--androidmanifest file Permission Declaration, permission check mechanism
The system checks the order of the operator's permissions: First, the permission name is judged, and if it is empty, the permission_denied is returned directly; second, the UID is determined, if the UID is 0 or the UID of the system service, no permission control is done. If the UID differs from the request UID in the parameter, then the permission_denied is returned; By calling the Packagemanagerservice.checkuidpermission method to determine whether the UID has the appropriate permissions, the method will go to the XML's permission list and the system-level platform.xml to find it.
(3) Application signing mechanism-digital certificate: The system will not install unsigned apps, only apps with the same digital signature will be considered the same app when upgrading
(4) Linux kernel layer Security mechanism--uid, access rights control
(5) Android Virtual machine sandbox mechanism-sandbox isolation: Each app runs in a separate virtual machine, completely isolated from other apps

APK Anti-compilation
Use Apktool, Dex2jar, Jd-gui three tools to decompile and view the application source code

APK encryption
Proguard can be used not only to confuse code (rename classes, methods and properties with meaningless letters), but also to delete useless classes, fields, methods, and properties, and to delete useless annotations to maximize the optimization of bytecode files.
The following is a common Proguard configuration where the minifyEnabled property controls whether the Proguard is started, the proguardFiles property is used to configure the obfuscation file, it is divided into two parts, one is the system default obfuscation file, it is located <sdk>/tools/proguard/proguard-android.txt ; the other is a custom obfuscation file, The file can be found under the project's app folder, where the obfuscation rules for the introduced third-party dependency package are defined.

Buildtypes {
Release {
False
Proguardfiles getdefaultproguardfile (' Proguard-rules.pro ')
}
}

Android Performance optimization

1. Layout optimization
The smooth feeling of the human eye requires frames up to 40 frames per second to 60 frames, so almost every 16ms system will render and redraw the UI.
(1) Android system provides a tool to detect UI rendering time, "developer Options"-"Profile GPU Rendering"-"in screen as bars", this time a number of bar charts will be displayed, as shown in the left image below, each bar line contains three parts, Blue represents the time the display list was plotted, and red represents the time it takes for OpenGL to render the display list, and yellow represents the time the CPU waits for GPU processing. The green horizontal line in the middle represents VSync time 16ms, and you need to keep all bar charts under the green lines as much as possible.
(2) Over-drawing (Overdraw) is also a waste of CPU/GPU resources, the system also provides a detection tool Debug GPU Overdraw to see 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.

(3) Optimize the layout level, Google suggested in the document view tree height should not exceed 10 levels
Avoid nesting too many useless layouts:
① Reusing layout with tags
If you need to overwrite android:layout_xxx properties in the label like 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.
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.
(4) Hierarchy Viewer: Tools to view the view tree

2. Memory optimization
Typically, the memory we call refers to the ram of the phone, which includes the following parts:
(1) Register: Register is inside the CPU, cannot be controlled in the program;
(2) Stack: a reference to the basic data types and objects;
(3) Heap: storage objects and arrays, with virtual machine GC to manage;
(4) Static storage area: In a fixed location where the application is running, Java has a static storage area in memory to manage some special data variables, such as static data variables;
(5) Chang (constant pool): a virtual machine must maintain a constant pool for each class being mounted, which is an ordered set of constants used by this class, including direct constants (basic types, strings), and symbolic references to other types, fields, and methods.

Memory-Optimized instances
(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 or iterators; [I don't know why]
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.

3. Other auxiliary tools
(1) Lint tools: Code hinting tools that you can use to discover hidden problems in your code
(2) Memory Monitor tool: RAM monitoring Tool
(3) TraceView Tool: Visual performance Survey Tool, which is used to analyze TraceView logs
(4) Mat Tool: Memory Analysis tool
(5) Dumpsys command: This command can list the Android system related information and service status, can use a lot of configuration parameters, common are:
activity: Displays information for all activity stacks;
meminfo: Displays memory information;
battery: Displays battery information;
package: Display package information;
wifi: Displays wifi information;
alarm: Display alarm information;
procstats: Displays the memory status.

The fourth Chapter analysis System Information and security mechanism performance optimization of activity and activity call stack

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.