Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Android project and coding specifications     - using the ssh command to check the socket / Network Connections (Linux)

- To explore the caching mechanism for Android ListView (Programming)

- By way of a binary installation innobackupex (Database)

- Linux SSH commands (Linux)

- Bash command substitution (Programming)

- Build your own Python coding environment (Linux)

- Xshell upload files to achieve Windows host Linux (Linux)

- Linux iptables: Composition Rules (Linux)

- Linux module mechanism of (Programming)

- Linux port scanning (Linux)

- How to experience Unity 8 Mir on Ubuntu 16.04 (Linux)

- Android thread mechanism --AsyncTask (Programming)

- Linux MultiPath software implementation instructions (Linux)

- Actual custom yum repository ---- gem commands commonly used parameters (Linux)

- Enterprise Encrypting File System eCryptfs Comments (Linux)

- dd command: do hard disk IO performance test (Linux)

- Vim simple configuration (Linux)

- Install Gnome Flashback Classic Desktop on Ubuntu 14.10 / Mint 7 (Linux)

- To assign multiple IP addresses NIC on the CentOS 7 (Linux)

- Linux character device - a simple character device model (Linux)

  Android project and coding specifications
  Add Date : 2018-11-21      
  File Naming

Class naming

Named hump should follow nomenclature
For class inherits from Android components, the name should be changed to the end of the name component; for example: SignInActivity, SignInFragment, ImageUploaderService, ChangePasswordDialog.

The file named Res

Resource file format should be named in lowercase + underscore (_) is.

Image files

The following is an image file naming conventions

Asset Type Prefix Example
Action bar ab_ ab_stacked.9.png
Button btn_ btn_send_pressed.9.png
Dialog dialog_ dialog_top.9.png
Divider divider_ divider_horizontal.9.png
Icon ic_ ic_star.png
Menu menu_ menu_submenu_bg.9.png
Notification notifi_ notifi_bg.9.png
Tabs tab_ tab_pressed.9.png
For icon naming convention

Asset Type Prefix Example
Icons ic_ ic_star.png
Launcher icons ic_launcher ic_launcher_calendar.png
Menu icons and Action Bar icons ic_menu ic_menu_archive.png
Status bar icons ic_stat_notify ic_stat_notify_msg.png
Tab icons ic_tab ic_tab_recent.png
Dialog icons ic_dialog ic_dialog_info.png
The choice of state naming convention

State Suffix Example
Normal _normal btn_order_normal.9.png
Pressed _pressed btn_order_pressed.9.png
Focused _focused btn_order_focused.9.png
Disabled _disabled btn_order_disabled.9.png
Selected _selected btn_order_selected.9.png
Layout file

Android layout file name components should be used for matches, but this should begin with the name of the component. For example, if we SignInActivity, create layout files that should be the name of the layout file is activity_sign_in.xml.

Component Class Name Layout Name
Activity UserProfileActivity activity_user_profile.xml
Fragment SignUpFragment fragment_sign_up.xml
Dialog ChangePasswordDialog dialog_change_password.xml
AdapterView item - item_person.xml
Partial layout - partial_stats_bar.xml
A special case is create a layout for the Adapter in the child when, for example, to display the contents of the ListView. In this case, the prefix layout file should be item_
There should be noted that when there is a special case, and that is creating a layout in which a small piece of the layout, in which case you should use the prefix partial_

File menu

Similar to the naming rules layout files, menu files, and the name of Android components should be used for matches. For example, when we create a menu file UserActivity, the name of the file that the menu should be activity_user.xml
Naming convention is not the word menu as part of the name, because these files are already stored in the file menu.


The values ​​in the resource file folder naming should be in the plural. For example, strings.xml, styles.xml, colors.xml, dimens.xml, attrs.xml

Code Specification

Java language specification

Do not neglect to handle exceptions

Never write the following code

void setServerPort (String value) {
    try {
        serverPort = Integer.parseInt (value);
    } Catch (NumberFormatException e) {}

Do not think your code will never trigger abnormal or insufficient to deal with such or such like the above code in your code leaving a gap for others to help you in the future to fill in. You must follow the specification to capture every an exception. You can also view the official Android documentation describes.

Do not catch general exception

Never write the following code

try {
    someComplicatedIOFunction (); // may throw IOException
    someComplicatedParsingFunction (); // may throw ParsingException
    someComplicatedSecurityFunction (); // may throw SecurityException
    // Phew, made it all the way
} Catch (Exception e) {// I'll just catch all exceptions
    handleError (); // with one generic handler!

You can view the Android specific reasons described in official documents

Do not use finalizers

Do not use finalizers (do not know finalize can be viewed here). Even finalizer ultimately be called, but when it will do the call is not guaranteed. In most cases, you can replace good exception catching mechanism finalizer. If in some cases you have to use it to define a close () method (or similar) and then accurately explain when the method is called to.

Specification reference

This is a bad reference writer: import foo *;.
It is a qualified reference writer: import foo.Bar;
More information here

Java style guide

Definition and Nomenclature variables

Variables should define the location in the file header, and should follow the naming rules.

Private, non-static variables should have been named at the beginning of m
Private, static variables should be named at the beginning of s
The remaining variables should have been the beginning of lowercase letters
Static constants should be all uppercase letters underlined name format. For example, ALL_CAPS_WITH_UNDERSCORES.
Examples are
public class MyClass {
    public static final int SOME_CONSTANT = 42;
    public int publicField;
    private static MyClass sSingleton;
    int mPackagePrivate;
    private int mPrivate;
    protected int mProtected;
The English acronyms also look to make a word

Good Bad
XmlHttpRequest XMLHTTPRequest
getCustomerId getCustomerID
String url String URL
long id long ID
Use spaces to indent

Use four spaces to indent the code block

if (x == 1) {
    x ++;

Use eight spaces to code line breaks

Instrument i =
        someLongExpression (that, wouldNotFit, on, one, line);

Use braces

The opening brace should be on the same line with the code in its previous

class MyClass {
    int func () {
        if (something) {
            // ...
        } Else if (somethingElse) {
            // ...
        } Else {
            // ...

If the conditional statement with the results of the statement and just to its length is less than the maximum length of the same line on the same line, you can omit the braces

if (condition) body ();

Error examples

if (condition)
    body (); // bad!


Application Notes

According to the official Android documentation, in Java annotations for some pre-determined criteria are applied

@Override: This annotation must rewrite time and any time you want to achieve or a parent class with, for example, when you use @inheritdocs tag, and is derived from a class rather than an interface, you must. while also adding @Override label on this method.
@SuppressWarnings:. When the label only in the encounter can not ignore the warnings of conditions can only be used if a warning in line with "Can not ignore" conditions, the label must be required to use, in order to ensure that all warnings reflect the actual problems in the code.
More on specifications please refer to the notes here
Notes format

Classes, methods, and constructors: annotations are used when classes, methods, constructors, annotations should be located in the following comments, and each comment as a form of a line is as follows.

/ * This is the documentation block about the class * /
public class MyAnnotatedClass {}
Object: Notes should be kept with the object in the same row, unless the bank has reached the maximum number of characters is limited.

@Nullable @Mock DataManager mDataManager;
Limit the scope of variables

The scope of local variables should be kept to a minimum. This increases code readability and maintainability, and reduce the probability of error.
Local variables should try when it was first called to be declared out. And when you declare a local variable that should be initialized variable, if you do not have enough information to initialize the variable, it should be postponed until the statement has sufficient information to this variable initialization time. more information can be found here

Specification log

Please use the company-wide LogUtil class instead of native Android Log class to print the log.

Specification class members arranged

This part is not mandatory requirements, but the use of a logical and common way to arrange the class members, can enhance the readability of the code

Rewriting and callback functions (including public and private)
Public function
Private functions
Internal interfaces and inner classes

public class Child extends Parent {

    private static final int CONSTANT = 1;

    private String mName;
    private int mAge;

    public Child (String name, int age) {
        mName = name;
        mAge = age;

    public void changeName () {

    public void setName (String name) {
            mName = name;

    private void setSomething () {

    static class AnInnerClass {


If your class is derived from Android components, such as Activity and Fragment, good habits are the life cycle of the assembly to rewrite the method. For example, if you have a realization of the Activity onCreate (), onDestroy (), onPause () and onResume (), then the correct order:

public class MainActivity extends Activity {

    // Order matches Activity lifecycle
    public void onCreate () {}

    public void onResume () {}

    public void onPause () {}

    public void onDestroy () {}


Order function arguments

When writing Android code function with parameters Context is very common. If this happens, then you must Context as the first parameter.
Corresponding callback interface should always as the last parameter of the function

// Context always goes first
public User loadUser (Context context, int userId);

// Callbacks always go last
public void loadUserAsync (Context context, int userId, UserCallback callback);

String constant naming

Android SDK contains many of the key elements required for example, SharedPreferences, Bundle and Intent. Even in a small app written application, it will also generate a lot of string constants.
When using the above components, you have the string defined as static final, and they should follow the prefix naming rules:

Element Field Name Prefix
SharedPreferences PREF_
Bundle BUNDLE_
Fragment Arguments ARGUMENT_
Intent Extra EXTRA_
Intent Action ACTION_
Although Fragment.getArguments () is the return of a Bundle, but in order to distinguish, so use ARGUMENT_ as its prefix.

// Note the value of the field is the same as the name to avoid duplication issues
static final String PREF_EMAIL = "PREF_EMAIL";
static final String BUNDLE_AGE = "BUNDLE_AGE";
static final String ARGUMENT_USER_ID = "ARGUMENT_USER_ID";

// Intent-related items use full package name as value
static final String EXTRA_SURNAME = "com.myapp.extras.EXTRA_SURNAME";
static final String ACTION_OPEN_USER = "com.myapp.action.ACTION_OPEN_USER";

Fragment of parameters and Activity

When the data is passed to the Fragment and Activity by Intent or Bundle time, Key's name must follow the above naming convention.
When the Activity or Fragment need to accept parameters when you need to create a public static method to create associated Intent or Fragment.
Activity of the case, usually a method named getStartIntent ():

public static Intent getStartIntent (Context context, User user) {
    Intent intent = new Intent (context, ThisActivity.class);
    intent.putParcelableExtra (EXTRA_USER, user);
    return intent;

Fragment of the case, usually a method named newInstance (), to create the parameters passed Fragment

public static UserFragment newInstance (User user) {
    UserFragment fragment = new UserFragment;
    Bundle args = new Bundle ();
    args.putParcelable (ARGUMENT_USER, user);
    fragment.setArguments (args)
    return fragment;

Such methods should be declared before in front of the class, onCreate () method: Note 1
Note 2: if we have declared more methods, then the Key Intent or Bundle declaration should be private, because no class outside to use.

Line length limit

The length of the line of code should not be more than 100 characters, if a line of code is too long, there are usually two ways to reduce the length of the code:

Extracting a local variable or method (recommended)
By changing a line of code line into multiple lines
There are two exceptions to the line of code can allow more than 100 characters

Unable to change lines of code, such as: Website URL
Statement of package and import
Specification wrap

There is also no standard mandatory line, but there are several more generic specification compliance can hope
When you want to change line operator at the time, we should wrap before operator, for example:

int longName = anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne
        + TheFinalOne;

However, the above rules do not apply to the = operator should wrap after the equality operator, for example:

int longName =
        anotherVeryLongVariable + anEvenLongerOne - thisRidiculousLongOne + theFinalOne;

The method under chain case
When multiple methods on the same line together when the chain has become the method. For example, under Builder mode, each method should be independent in a row, and should wrap before.

Picasso.with (context) .load ( "http://ribot.co.uk/images/sexyjoe.jpg") .into (imageView);

Picasso.with (context)
        .load ( "http://ribot.co.uk/images/sexyjoe.jpg")
        .into (imageView);
The case where a plurality of parameters
When a function of many parameters and parameter too long, we should, after wrapping.

loadPicture (context, "http://ribot.co.uk/images/sexyjoe.jpg", mImageViewProfilePicture, clickListener, "Title of the picture");

loadPicture (
        "Title of the picture"
For the specification in RxJava

The method also requires the chain Rx wrap each operation must be independent of one line, and should wrap before.

public Observable syncLocations () {
    return mDatabaseHelper.getAllLocations ()
            .concatMap (new Func1 > () {
                 public Observable call (Location location) {
                     return mRetrofitService.getLocation (location.id);
            .retry (new Func2 () {
                 public Boolean call (Integer numRetries, Throwable throwable) {
                     return throwable instanceof RetrofitError;

XML specification

Use self-closing tags

When there is no other element in a XML element, you should use self-closing tags
this is correct:

    android: id = "@ + id / text_view_profile"
    android: layout_width = "wrap_content"
    android: layout_height = "wrap_content" />

this is wrong:

<-! Don 't do this -!>
    android: id = "@ + id / text_view_profile"
    android: layout_width = "wrap_content"
    android: layout_height = "wrap_content">


Named Resources

ID and name of the resource should be lowercase + underscore format

The name ID

ID should have control name as a prefix to name, for example:

Element Prefix
TextView text_
ImageView image_
Button button_
Menu menu_
ImageView example:

    android: id = "@ + id / image_profile"
    android: layout_width = "wrap_content"
    android: layout_height = "wrap_content" />

Menu examples:

             android: id = "@ + id / menu_done"
        android: title = "Done" />



String name should have been able to identify a prefix of ordinary skill to do at the beginning, for example, registration_email_hint or registration_name_hint If a string does not belong to any field, it should follow the following rules:

Prefix Description
error_ An error message
msg_ A regular information message
title_ A title, i.e. a dialog title
action_ An action such as "Save" or "Create"
Style and Theme

Unlike other resource naming conventions, Style names in nomenclature should follow the hump


color color naming should follow the format lowercase + underscore

Android provides performance coding standards

Do not use enum in Android program

Although enum is convenient, but it will produce more than twice the memory consumption than using static variables, it is strongly recommended not to use the official Android in the Android application to enum inside.
Use Android Typedef Annotations can replace enum, please refer to the specific use of payment here

About array traversal

static class Foo {
    int mSplat;

Foo [] mArray = ...

// Slowest, most consumption
public void zero () {
    int sum = 0;
    for (int i = 0; i         sum + = mArray [i] .mSplat;

public void one () {
    int sum = 0;
    Foo [] localArray = mArray;
    int len ​​= localArray.length;

    for (int i = 0; i         sum + = localArray [i] .mSplat;

// Recommended
public void two () {
    int sum = 0;
    for (Foo a: mArray) {
        sum + = a.mSplat;
zero () is the slowest method because every time to get the length of the array is optimized when JIT also can not traverse when the array.
one () a little faster, because all the data stored in local variables out there, avoiding lookup only provides the length of the array of performance has been some improvement
two () in the absence of JIT is the fastest device in, but there is a device in the JIT in one () is difficult to distinguish from top to bottom. It uses the Java 1.5 version of the enhanced version of the syntax
So it should be used by default for an enhanced version of the loop.
- Ubuntu 12.04 installation NVIDIA GTX750 graphics driver (Linux)
- How to install Nginx on FreeBSD 10.2 as an Apache reverse proxy (Server)
- SSH port forwarding application (Server)
- Category prevent DoS attacks against Linux (Linux)
- To install the iNode client on UbuntuKylin 13.10 (Linux)
- Command-line based tools for better alternatives (Linux)
- How to understand the difference between synchronous and asynchronous non-blocking blocking (Programming)
- Setting up Linux machine through a proxy firewall (Linux)
- MySQL 5.6 Open full query log (Database)
- Use Visual Studio 2015 to develop Android program (Programming)
- Docker + OpenvSwitch build experimental environment VxLAN (Server)
- Linux file permissions bit forced bits and adventure Comments (Linux)
- Ubucompilator-Ubuntu, Debian, Linux Mint created deb package of graphical tools (Linux)
- SLF4J Tutorial (Programming)
- Windows7 system using Vagrant to build Linux virtualized development environment (Linux)
- Perl said method B if A judge (Programming)
- Network security system (Network)
- MySQL DATE_FORMAT () function (Database)
- Analysis of memory mapping process in Linux x86-32 mode (Linux)
- Stunning exclamation point at the Linux command line (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.