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
- 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;
- Allowed in the same two complex layout of the same logical group, you must be a separate pumping
include
; - Subclass specific method does not allow the parent class appears, if required, can define abstract superclass method, referred to subclasses to implement;
- Not allowed
Activity
within multi-Fragment
direct communication between, mustActivity
transit;
recommend
- Recommended MVP or MVVM architecture;
- We recommend the use of
Kotlin
language; - Modular alternative file classification categories, convenient to quickly find relevant content modules, for example:
LoginActivity/LoginPreenter/LoginHttpRequest/LoginBean/LoginAdapter
file belongs to the same login and other modules into a folder, rather than allactivity
in one folder, alladapter
in one folder.
naming method
Enforcement
- Chinese naming is not allowed;
- java / kotlin files large hump, examples:
LoginActivity.kt, NewsAdapter.kt, NewsBean.java
; - layout / drawable / anim / style resource file and the like underlined lowercase + manner, for example:
login_activity.xml, login_logo.png
; - Large hump class definitions, examples:
class LoginPresenter {}, class NewsBean {}
; - Object small hump, examples:
LoginPresenter loginPresenter, NewsBean newsBean
; - Static constant use all uppercase + underlined ways, for example:
public static final boolean IS_RELESAE = true
; - Kotlin use layout controls id must use small hump ways, for example:
android:id="@+id/tvLogin"
recommend
-
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>
-
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
- All newly defined class / method, the default is written
private
, marked only look at the situation when you need to reference other classespublic, protected, package-private
;
recommend
- java parent class definitions defined if the subclass overrides cause problems, adding
final
keywords;
Notes related
Enforcement
- 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(...){} } 复制代码
- Note variables are not allowed consistent with the class / method as comments;
- Method comments are not allowed
@params, @return
parameter describes the error situation must be updated in real time;
recommend
- Some logic recommended
/* */
way; - Methods / Parameters proposed to add
@Nullable, @NotNull, @UiThread
such as notes;
Code style
While this directory git there AndroidCodeStyleSetting.jar
profile, 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 AndroidStudio
submit a version control right window Before Commit
by checking the Reformat code
option.
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
- Allowed transfer of data over 1M Intent communication mode or external relay Presenter EventBus transfer may be employed;
- 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)
; - In the Activity / Service / BroadcastReceiver if there is time-consuming operation, it must be multi-threaded processing;
- Internal application sends a broadcast, only
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
not allowedcontext.sendBroadcast(intent)
, to avoid external applications interception; - Is not allowed in
Application
the cache data, global data may be shared using apresenter
store, or usedSharedPreference
to read and write; Activity
OrFragment
dynamic registrationBroadCastReceiver
time,registerReceiver
andunregisterReceiver
must appear in pairs;
recommend
Activity#onPause/onStop
In conjunction withisFinishing
the release of resources to execute judgment, the timing will be free later on the implementation ofActivity#onDestroy()
the execution;- Do not
Activity#onPause
perform time-consuming operation, this will lead to a jump Caton interface, can be placedActivity#onStop
in execution;
UI / layout
Enforcement
- Xml layout preferentially used
ConstraintLayout
, ensure complete without nesting portion comprises explicit and implicit control while 99% of demand, including the layout requirements; - Do not allow the use of
ScrollView
parcelsListView/GridView/ExpandableListVIew
and other lists View, multi-use complex polynomial list canItemType
be processed;
recommend
- In the
Activity
display the dialog box or pop-up blanket, to make useDialogFragment
, insteadDialog/AlertDialog
, with the convenience ofActivity
life cycle management pop life cycle;
Process / thread / message push
Enforcement
- When the presence of multiple processes,
Application
the initialization code are processed according to the process, to avoid unnecessary initialization operations; - When creating a new thread, the thread pool must be a way, it does not allow the use
new Thread()
of way; Activity/Fragment
Is usedHandler
, you must use a static inner classes + WeakReferences manner or in aonStop
callhandler.removeCallbacksAndMessages
;
recommend
- To share data among multiple processes using
ContentProvider
alternativeSharedPreferences#MODE_MULTI_PROCESS
;
File / database
Enforcement
- 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)
; - When using an external memory, the external memory must check the availability of:
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
; - Database
Cursor
after use must be closed in order to avoid memory leaks;
recommend
SharedPreference
Storing only simple data types, do not store complex data, such as data json / Bitmap coding;SharedPreference
When submitting data, try to useEditor#apply()
insteadEditor#commit()
;
Image / Animation
Enforcement
- It must be processed in the child thread when loading big picture, otherwise the card UI;
- In
Activity.onPause()/onStop()
the close the currentactivity
animation being executed;
recommend
- Android recommendations into image format WebP, APK can reduce the volume;
- Try not to use animation
AnimationDrawable
, occupy a lot of memory; - Used
ARGB_565
instead ofARGB_888
, reduce the memory footprint; - When the
Animation
end of the execution, callingView.clearAnimation()
the release of resources;
safety
Enforcement
- On-line package must be confused;
- Encryption and decryption keys / salt does not allow hard-coded into the code, obtaining prevent decompilation; not allowed to accept any certificate;
- Use of Android
AES/DES/DESede
encryption algorithms, do not use the default encryption modeECB
, the display should specifyCBC/CFB
the encryption mode; - To ban the printing of sensitive information to log in;
- In the application must ensure that the publication
android:debuggable
was false; - Use must
X509TrustManager
subclasscheckServerTrusted
the legitimacy of the certificate server function efficacy, - You must be
android:allowbackup
property tofalse
prevent theadb backup
export application data;
Reproduced in: https: //juejin.im/post/5d098f956fb9a07eb051c51e