Getting started with Android4: Best Practices

Source: Internet
Author: User


Performance Improvement

There are two basic rules for writing valid code:

1: Don't Do What You Don't Need To Do.
2: do not allocate unnecessary memory.
 
Avoid creating unnecessary objects, such:

1: When extracting strings from a group of input data, try to return the child string of the source data instead of creating a copy.
2: If you have a method to return a String, and you know that the result will be appended to StringBuffer all the time, change your signature and implementation, and directly append it in this function, avoid creating temporary objects.
3: Cut the multi-dimensional array into a parallel one-dimensional array
4: an int array is better than an Integer array. A common fact is that two parallel int arrays are much more efficient than an array of (int, int) objects. For other raw data types
Try to use the Native method, for example:

When processing strings, do not hesitate to use strings such as String. indexOf (), String. special methods such as lastIndexOf (). These are typical methods implemented using C/C ++ code. They can be 10-times faster than Java loops that implement the same function.
The implementation class is preferred, not the interface

For embedded systems, calling a method through interface reference takes two times more time than calling a virtual method through a specific type of reference.
Except for public APIs, good APIs have less performance considerations.
Select static instead of virtual

If you do not need to access an object field, make your method a static method. It can be called more quickly because it does not require a virtual method to call it indirectly.
Avoid internal Getter/Setter

In Android, virtual method calls are expensive, and instance field searches are more expensive. It is reasonable to provide gettter and setter in public interfaces following the general object-oriented programming practices, but you should directly access fields in a class.
 
Accessing object fields is much slower than accessing local variables, as shown in the following section:

Java code:
View copies to clipboard and print
For (int I = 0; I <this. mCount; I ++)
DumpItem (this. mItems [I]);
It should be written as follows:
Int count = this. mCount;
Item [] items = this. mItems;
For (int I = 0; I <count; I ++)
DumpItems (items [I]);
(We use an explicit "this" to indicate that this is a member variable .)
Similarly, do not call methods in the second clause of the for statement. For example, the following code will execute getCount () every iteration, which is a huge waste. You can cache its value as an int.
Java code:
View copies to clipboard and print
For (int I = 0; I <this. getCount (); I ++)
DumpItems (this. getItem (I ));
Cache query fields. Generally, if you want to access an instance field multiple times, a good habit is to create a temporary variable. For example:


Java code:
View copies to clipboard and print
Protected void drawHorizontalScrollBar (Canvas canvas, int width, int height ){
If (isHorizontalScrollBarEnabled ()){
Int size = mScrollBar. getSize (false );
If (size <= 0 ){
Size = mScrollBarSize;
}
MScrollBar. setBounds (0, height-size, width, height );
MScrollBar. setParams (computeHorizontalScrollRange (),
Computehorizontalscroloffset (),
ComputeHorizontalScrollExtent (), false );
MScrollBar. draw (canvas );
}
}
This is a separate search for the member field mScrollBar four times. By caching the mScrollBar to a local variable, the four member field searches are changed to four local variable references, which is more efficient.
Similarly, method parameters as local variables share the same performance characteristics.

 
The declared constant is static final, mainly for Attribute fields. You can declare the local variable as final, but this does not actually improve the performance.
Use an enhanced For loop statement
The enhanced For statement performs well For arrays, but you must be careful when using iterable objects because additional objects are created. For ArrayList, you 'd better traverse it directly, but For other collections, the enhanced For loop statement will be equivalent to the explicit iterative usage.
Avoid using the Enum type
Avoid using the Float Type
Embedded processors rarely support hardware floating point. Therefore, all "float" and "double" operations are performed on software. Some basic floating point operations may take several microseconds.
Avoid using JNI
Supports multiple screens

In actual development, the screen resolution may be different due to the size of different mobile phones, which may cause many problems, such:

1: images are displayed on different devices in different sizes.
2: Layout is displayed on different devices and may be deformed.
Some basic solutions:

1: Try to use sp as the unit for fonts, and try to use dp or dip for others.
2: Use wrap_content, fill_parent, or dp to define the layout size.
3: Optimal Proportion of image files corresponding to devices of different density.
For devices with four density options: low-dpi, medium-dpi, high-dpi, and extra high-hdpi, the size of the image file allocated to various density should meet the following proportions: 3: 4: 6: 9. that is, to conform to the density ratio (120: 160: 240: 360 ).
For example, we want to use a 48*48 image file on a device with a density of DPI. For devices of other density, the image files we need to prepare are:

Low-density (120 dpi): 36 × 36
Medium-density (160 dpi): 48 × 48
High-density (240 dpi): 72 × 72
High-density (360 dpi): 96 × 96
4: provide the specified layout File For devices of each size as needed.
5: provide different image files for each density device as needed
6: Do not use the absoluteLayout Layout
UI Best Practices

This is a copy from Moto. The best practices for Android UI are as follows:

1: Read the UI Guidelines (UI guideline)
2: Understand and design the touch mode
3: supports multiple interactive modes (such as keyboard, trackball, and touch screen)
4: Use notifications and window shade)
5. Interaction between applications is supported.
6: Keep your user operations fast and sensitive
7. Use form parts and folders
8. Change the screen direction
9: clever use of images
10: Use a multi-device layout
This is an official Android developer blog with the Best Practices for Android UI.

No

1. Do not copy your uidesign on other platforms. It should make users feel like they are using an Android software, balancing your trademark display and overall platform View
2. Do not over-use the Modal Dialog Box
3. Do not use a fixed absolute positioning layout.
4. Do not use px units. Use dp or sp for text.
5. Do not use a small font.
Should

1. Create resources for high-resolution screens (better overall zoom-in ratio)
2. The elements to be clicked must be large enough
3. the icon design follows the Android standard.
4. Use appropriate spacing (margins, padding)
5. Support for D-pad and trackball navigation
6. correctly manage the activity Stack
7. Correctly handle screen direction changes
8. Use theme/style, size, and color resources to reduce unnecessary values
9. Cooperate with visual Interaction designers !!!
Design Philosophy

1. Clean but not easy
2. Focus on content rather than Modification
3. Consistent storage, making it easy for users to invest in IT and adding a little change
4. Use cloud services (to store and synchronize user data) to enhance user experience
Design Guidelines for excellent interfaces

1. Follow the user
2. display the correct content
3. Give the user appropriate feedback
4. Rule-Based Behavior Models
5. tolerate errors
Follow user

1. Understand your users (age, skills, culture, requirements for your applications, devices used, and how to use devices whenever and wherever)
2. 'user preview' design mentality (users are generally task-oriented behavior models)
3. Earlier, more frequently tested by real users
Display correct content

1. The most common operations must be visible and available to users as soon as possible.
2. Less commonly used functions can be placed in the menu
 
Give users appropriate feedback

1. Interactive UI elements must reflect at least four different States (default, disabled, focused, and pressed)
2. Ensure that the operation results are clearly visible.
3. Give more progress prompts to users, but do not interfere with their current operations.
Rule-based behavior patterns

1. The behavior mode follows the user's expectations (correct operation of the activity stack, display the information and actions that the user expects to see)
2. Use the appropriate method to enhance the feature visibility (clickable elements should look as clickable)
3. If you need complicated operations to complete a task, rethink your design !!!
Error Tolerance

1. Only meaningful operations are allowed (some buttons are disabled as appropriate)
2. Minimize non-rollback operations
3. it is better to allow rollback (undo) than to use a confirmation dialog box (in fact, the confirmation dialog box should be used as few as possible, which is a disturbance to the user). If an error occurs, then it will happen.
Design Considerations

1. physical size of the screen
2. Screen Density
3. Screen direction (vertical and horizontal)
4. Main UI interaction methods (touch screen or D-pad/trackball)
5. Soft or physical keyboard
6. It is very important to understand the differences between different devices!
7. Read about CDD and learn the possible differences between devices.
8. Understand screen size and density Classification
 
Response sensitivity (Designing for Responsiveness)

Some areas where the application is not responsive include: slow response, long suspension or freezing, or a long time to process input.
On Android, if your Application is Not responsive for a period of time, the system will display you a dialog box called ANR: Application Not Responding.
What triggers ANR: In Android, the responsiveness of applications is monitored by the system services of Activity Manager and Window Manager. When it detects one of the following situations, Android displays ANR for specific applications:
1: no response to the input event within 5 seconds (for example, press the button and touch the screen)
2: BroadcastReceiver fails to be executed within 10 seconds.
How to Avoid ANR

Do as few things as possible in any method running in the main thread. In particular, the Activity should do as few creation operations as possible in its key lifecycle methods (such as onCreate () and onResume. Potential time-consuming operations, such as network or database operations, or high-time computing such as bitmap size change, should be in the Child thread (or take database operations as an example, through asynchronous request).
Enhanced Response Sensitivity

In general, 100 to MS is the time threshold for the user to perceive the block in the application. Here are some additional tips to avoid ANR and help make your application look responsive.
1: If your application is entering a working background for the response user, it can display the working progress (ProgressBar and ProgressDialog are useful in this case ).
2: especially for games, mobile computing is performed in sub-threads.
3: If your application has a time-consuming initialization process, consider displaying a Splash Screen or quickly displaying the main Screen and asynchronously filling in the information. In both cases, you should display the progress in progress so that users do not think the application is frozen.
Introduction: Even if your application is fast and responsive, some designs still pose problems to users-interactions with other applications or dialogs that are not planned in advance, unexpected data loss, unexpected blocking, and so on. In short, you should do your best to develop an application that interacts smoothly with the system and other applications.
Common fluency problems:

1: Background processing of an application-for example, a Service or BroadcastReceiver-a dialog box is displayed to respond to some events. This may not seem serious. However, when your application runs on a real machine, it is possible that the background processing displays a dialog box when your application does not get the user focus. Therefore, a dialog box for your application may appear after an active application, or a dialog box is displayed to capture the focus from the current application, regardless of what the current user is doing (for example, calling ). In this case, you should use Notification instead of capturing the focus and interrupting the user.
2: In another example, the onPause () and other life cycle methods of the Activity are not correctly implemented, resulting in unexpected loss of status or user data.
Smooth Design Guide

1: Do not discard data

If other activities appear when the user is editing data in your application, the data may be lost when your application is killed.
Android method: Android applications that can receive and edit user input should rewrite the onSaveInstanceState () method and properly save their statuses. Persistent data should be stored in the onPause () method.
2: do not expose raw data

Expose raw data and require other applications to understand the format of your data. If you change the format, you will destroy those applications that are not synchronously updated.
The "Android method" is to create a ContentProvider to expose your data to other applications in a clear, thoughtful, and maintainable API method. Using ContentProvider is like inserting a Java interface to separate and assemble two highly coupled codes. This means that you can modify the internal data format without modifying the interfaces exposed by ContentProvider. This will not affect other applications.
3: Do not interrupt the user

If the user is running an application (such as the Phone Program), it is determined that the purpose of user operations is safe. This is why you must avoid creating an Activity, but directly respond to user input in the current Activity.
That is to say, do not call callActivity () in BroadcastReceiver or in a Service running in the background (). This will interrupt the currently running application and cause the user to get angry. Even worse, your Activity may become a "button robber", stealing the input that the user wants to provide to the previous Activity. Depending on what your application is doing, this may be bad news.
Instead of directly creating the Activity UI in the background, you should use NotificationManager to set Notification. They appear in the status bar, and users can click them when they are idle to view what your application shows to him.
(Note: If your Activity is already in the foreground, the above will not apply: at this time, for user input, the user expects to see the next Activity to respond .)
4: Are there too many things to do? Done in the thread

If your application needs to perform some expensive or time-consuming computing, you should try to move it to the thread as much as possible. This will prevent users from displaying the Terrible "Application Not Responding" dialog box.
5: Do not overload an Activity

Any worthy application may have several different screens. When designing your application, you can think of your application as a collection of Activity objects. In the long run, this will make your code easier to maintain.
6: extended system theme

When designing your UI, you should try to avoid too many theme. On the contrary, the same topic is used. You can rewrite or extend the theme part you need, but at least start with the same UI as other applications.
7: design your UI to handle multiple screen resolutions

Different Android devices may support different screen resolutions. Make sure that your layout and images are displayed flexibly on different device screens.
8: The network is slow.

You should write your code according to the minimal network access and bandwidth.
9: Do not assume the touch screen or keyboard

When creating an application, do not assume a specific keyboard layout-unless you really want to limit that your application only runs on certain devices.
10: Saving Device batteries


Author: hello spring

Related Article

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.