Android summary specification (refer to Ali specification, only for internal company)

Foreword

A qualified code should not just be satisfied to achieve the function, should follow good norms follow good coding standard in favor of:

  • To enhance the stability of the program, to reduce the risk of code, reduce the failure rate;
  • Increased scalability, greatly improve maintenance efficiency;
  • Uniform standards, many people work together to enhance efficiency;
  • Convenient new quick start, ensure that the project schedule when the project team changed;

Here comb Android development process in some places that need attention, including a plurality of sections, the other based on the binding strength of two types:

  • Forced: If you do not comply with the code can lead to serious confusion, post-maintenance complex, even a serious bug;
  • Recommended: Failure to comply could lead to code description is unclear, difficult to understand, resulting in more functional maintenance more difficult problems;

The following is the text of specification


Architecture-dependent

This is part of the overall project requirements, including system design, naming, visibility, comments, coding style and other parts.

system design

Enforcement

  1. When two missing leads to several changes to the logic blocks are not allowed to be out of public methods difference control parameters, to avoid modification;
  2. Allowed in the same two complex layout of the same logical group, you must be a separate pumping include;
  3. Subclass specific method does not allow the parent class appears, if required, can define abstract superclass method, referred to subclasses to implement;
  4. Not allowed Activitywithin multi- Fragmentdirect communication between, must Activitytransit;
recommend
  1. Recommended MVP or MVVM architecture;
  2. We recommend the use of Kotlinlanguage;
  3. Modular alternative file classification categories, convenient to quickly find relevant content modules, for example: LoginActivity/LoginPreenter/LoginHttpRequest/LoginBean/LoginAdapterfile belongs to the same login and other modules into a folder, rather than all activityin one folder, all adapterin one folder.

naming method

Enforcement

  1. Chinese naming is not allowed;
  2. java / kotlin files large hump, examples: LoginActivity.kt, NewsAdapter.kt, NewsBean.java;
  3. layout / drawable / anim / style resource file and the like underlined lowercase + manner, for example: login_activity.xml, login_logo.png;
  4. Large hump class definitions, examples: class LoginPresenter {}, class NewsBean {};
  5. Object small hump, examples: LoginPresenter loginPresenter, NewsBean newsBean;
  6. Static constant use all uppercase + underlined ways, for example: public static final boolean IS_RELESAE = true;
  7. Kotlin use layout controls id must use small hump ways, for example: android:id="@+id/tvLogin"
recommend
  1. File / module using resources when naming + type of way, in order to quickly find relevant content, such as login page: LoginActivity.kt, login_activity.xml, login_logo.png, <string name="login_net_error">网络错误</string>, <color name="login_page_backgroud">#f3f3f3</color>

  2. id name used in the layout of java is recommended to use a small hump mode, and use the control type abbreviations at the beginning, for example: android:id="@+id/tvLogin"Appendix abbreviations commonly used controls:

    Controls abbreviation
    LinearLayout ll
    RelativeLayout rl
    ConstraintLayout cl
    ListView lv
    ScollView en
    TextView tv
    Button BTN
    ImageView iv
    CheckBox cb
    RadioButton rb
    EditText and

Visibility

Enforcement

  1. All newly defined class / method, the default is written private, marked only look at the situation when you need to reference other classes public, protected, package-private;
recommend
  1. java parent class definitions defined if the subclass overrides cause problems, adding finalkeywords;

Notes related

Enforcement

  1. Class / or complicated methods can not be seen from the name of the method must be intended to add comments, when the class / method to add comments, must use this type Notes:
    /**
    * Created by XXX on 2019/6/19.
    * 描述此类作用, 逻辑复杂的说明一下主要思路
    */
    public class LoginPresenter {
        /**
        * 用于进行网络请求
        * @params xxx XXX
        */
        public void doLoginRequest(...){}
    }
    复制代码
  2. Note variables are not allowed consistent with the class / method as comments;
  3. Method comments are not allowed @params, @returnparameter describes the error situation must be updated in real time;
recommend
  1. Some logic recommended /* */way;
  2. Methods / Parameters proposed to add @Nullable, @NotNull, @UiThreadsuch as notes;

Code style

While this directory git there AndroidCodeStyleSetting.jarprofile, for the unified style format code according to the import AndroidStudio.

Formatting habits at any time if there is no code to write code, you can AndroidStudiosubmit a version control right window Before Commitby checking the Reformat codeoption.


Specific modules related to Android

The main section includes several basic components, UI / layout, process / thread / push messaging, file / database, picture / animation, security and so on.

Android basic components

Enforcement

  1. Allowed transfer of data over 1M Intent communication mode or external relay Presenter EventBus transfer may be employed;
  2. Intent must be checked when implicitly start the target is present, it will lead to the collapse of the target is not found: if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ ONLY) != null);
  3. In the Activity / Service / BroadcastReceiver if there is time-consuming operation, it must be multi-threaded processing;
  4. Internal application sends a broadcast, only LocalBroadcastManager.getInstance(this).sendBroadcast(intent)not allowed context.sendBroadcast(intent), to avoid external applications interception;
  5. Is not allowed in Applicationthe cache data, global data may be shared using a presenterstore, or used SharedPreferenceto read and write;
  6. ActivityOr Fragmentdynamic registration BroadCastReceivertime, registerReceiverand unregisterReceivermust appear in pairs;
recommend
  1. Activity#onPause/onStopIn conjunction with isFinishingthe release of resources to execute judgment, the timing will be free later on the implementation of Activity#onDestroy()the execution;
  2. Do not Activity#onPauseperform time-consuming operation, this will lead to a jump Caton interface, can be placed Activity#onStopin execution;

UI / layout

Enforcement

  1. Xml layout preferentially used ConstraintLayout, ensure complete without nesting portion comprises explicit and implicit control while 99% of demand, including the layout requirements;
  2. Do not allow the use of ScrollViewparcels ListView/GridView/ExpandableListVIewand other lists View, multi-use complex polynomial list can ItemTypebe processed;
recommend
  1. In the Activitydisplay the dialog box or pop-up blanket, to make use DialogFragment, instead Dialog/AlertDialog, with the convenience of Activitylife cycle management pop life cycle;

Process / thread / message push

Enforcement

  1. When the presence of multiple processes, Applicationthe initialization code are processed according to the process, to avoid unnecessary initialization operations;
  2. When creating a new thread, the thread pool must be a way, it does not allow the use new Thread()of way;
  3. Activity/FragmentIs used Handler, you must use a static inner classes + WeakReferences manner or in a onStopcall handler.removeCallbacksAndMessages;
recommend
  1. To share data among multiple processes using ContentProvideralternative SharedPreferences#MODE_MULTI_PROCESS;

File / database

Enforcement

  1. API to get the file path using the system, to avoid the fight hand string, for example: android.os.Environment#getExternalStorageDirectory(), Context#getFilesDir()error Example: File file = new File("/mnt/sdcard/Download/Album", name);
  2. When using an external memory, the external memory must check the availability of: Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
  3. Database Cursorafter use must be closed in order to avoid memory leaks;
recommend
  1. SharedPreferenceStoring only simple data types, do not store complex data, such as data json / Bitmap coding;
  2. SharedPreferenceWhen submitting data, try to use Editor#apply()instead Editor#commit();

Image / Animation

Enforcement

  1. It must be processed in the child thread when loading big picture, otherwise the card UI;
  2. In Activity.onPause()/onStop()the close the current activityanimation being executed;
recommend
  1. Android recommendations into image format WebP, APK can reduce the volume;
  2. Try not to use animation AnimationDrawable, occupy a lot of memory;
  3. Used ARGB_565instead of ARGB_888, reduce the memory footprint;
  4. When the Animationend of the execution, calling View.clearAnimation()the release of resources;

safety

Enforcement

  1. On-line package must be confused;
  2. Encryption and decryption keys / salt does not allow hard-coded into the code, obtaining prevent decompilation; not allowed to accept any certificate;
  3. Use of Android AES/DES/DESedeencryption algorithms, do not use the default encryption mode ECB, the display should specify CBC/CFBthe encryption mode;
  4. To ban the printing of sensitive information to log in;
  5. In the application must ensure that the publication android:debuggablewas false;
  6. Use must X509TrustManagersubclass checkServerTrustedthe legitimacy of the certificate server function efficacy,
  7. You must be android:allowbackupproperty to falseprevent the adb backupexport application data;

Reproduced in: https: //juejin.im/post/5d098f956fb9a07eb051c51e

Guess you like

Origin blog.csdn.net/weixin_33938733/article/details/93177275