preface

Code is the face of a programmer. A programmer with a door is a good programmer.

This article is excerpted from alibaba development manual, download address

This manual is divided into Java language specifications (following the “Alibaba Java Development Manual”), Android resource file naming and use, Android basic components, UI and layout, process, thread and message communication, file and database, Bitmap, Drawable and animation. According to the strength of the binding force, the regulations are divided into mandatory, recommended and reference categories:

Must abide by, breach of this agreement or will cause serious consequences;

Long-term compliance is conducive to the improvement of system stability and cooperation efficiency;

Full understanding, the guidance of technical awareness, is the direction of individual learning, team communication, project cooperation.

In the extended information of the protocol entry, the “description” extends and explains the content appropriately; What coding and implementation methods are advocated by “positive examples”; “Counterexamples” show minefields to watch out for and examples of mistakes.

Java language specification

Follow the “Alibaba Java Development Manual” manual, download the address

Second, Android resource file naming and use

  1. Resource files must be prefixed with modules.

  2. Layout Specifies the layout file name. Activity layout starts with module_activity layout starts with module_fragment Layout starts with module_dialog Dialog layout starts with module_dialog include ListView line layout starts with module_include. ListView line layout starts with module_list_item. RecyclerView item Layout starts with module_recycle_item The row layout of the starting GridView starts with module_grid_item

  3. The drawable resource names are named in lowercase letters and underscores (_). The resource names are stored in different drawable directories based on the resolution. You are advised to use only one set of resource names, for example, drawable-xhdpi. The rules are as follows: Module name _ Service Function Description _ Control description _ Control status qualifier:module_login_btn_pressed,module_tabs_icon_home_normal

  4. Anim resource name naming in lowercase word + the underlined way, USES the following rules: module name logical name _ _ [direction | serial number] tween animation resources: as far as possible in a generic animation name, such asModule_fade_in, module_FAde_OUT, module_PUSH_down_IN (animation + direction);Frame Animation resources: module + function name + sequence number if possible. Such as:module_loading_grey_001

  5. Color resource using #AARRGGBB format, writemodul_colors.xmlIn the file, the naming format follows the following rules: Module name_logical name_color. Such as:<color name="module_btn_bg_color">#33b5e5e5</color>

  6. Dimen resources are named with lowercase words and underscores (_) and written into the module_dimens. XML file using the following rules: Module name_Description. Such as:<dimen name="module_horizontal_line_height">1dp</dimen>

  7. Style resources are named with lowercase words and underscores and written to the module_styles. XML file using the following rules: Parent style name. Current style name. Such as:< style name = "ParentTheme ThisActivityTheme" >... </style>

  8. String resource files or text files must contain all characters in the module_strings. XML file. The strings are named using lowercase words and underscores (_) and the following rules apply: Module name_Logical name Example:moudule_login_tips,module_homepage_notice_desc

  9. The RESOURCE Id of a View component should be prefixed with the abbreviation of View. Common abbreviations are listed below

    For other control abbreviations, use lowercase letters and underscores. For example, ProgressBar is progress_bar and DatePicker is date_picker

10.Large-resolution images (more than 1000 dimensions) Large-resolution images are recommended to be managed in xxhdPI. Otherwise, the memory usage will increase exponentially. Note: In order to support a variety of screen sizes and densities, Android provides different resource directories for various screens. The configuration qualifiers that provide different bitmap drawable objects for different screen densities that can be used for density-specific resources (detailed below) include LDPI (low), MDPI (middle), HDPI (high), XHDPI (super high), XXHDPI (super super high), and XXXHDPI (super super high). For example, bitmaps for high-density screens should use drawable-hdpi/. According to the current screen size and density of the device, we will search for the most matching resources. If we put the high-resolution pictures into the low-density directory, the low-end computer will load too much picture resources, which may cause OOM, and it is also a waste of resources. There is no need to use large pictures on the low-end computer. Example: Save the 144 x 144 PNG file of the application icon to the drawable-xxhdpi directory. Example: Save the 144 x 144 PNG file of the application icon to the drawable-mhdpi directory

Basic Components of Android

The basic components of Android include activities, fragments, Services, BroadcastReceiver, ContentProvider, etc.

  1. The Activity, the data communication between the data quantity is big, avoid to use Intent + Parcelable way, consider EventBus alternatives, such as to avoid causing TransactionTooLargeException.

  2. The Activity#onSaveInstanceState() method is not an Activity lifecycle method and is not guaranteed to be called. It is used to store UI state when an Activity is accidentally destroyed. It can only be used to store temporary data, such as UI control properties, and should not be confused with persistent storage of data. Persistent storage should be implemented in Activity#onPause()/onStop().

  3. Through implicit Intent to jump between the Activity, must be inspected by resolveActivity before send Intent, avoid no suitable component, called ActivityNotFoundException abnormalities.

  4. Avoid time-consuming operations in the Service#onStartCommand()/onBind() methods and, if necessary, use IntentService or another asynchronous mechanism.

  5. Avoid time-consuming operations in BroadcastReceiver#onReceive(). If there are time-consuming operations, create IntentService instead of creating child threads in BroadcastReceiver. Note: Since this method is executed on the main thread, the UI will not be smooth if a time-consuming operation is performed. Call Context#registerReceiver (BroadcastReceiver, IntentFilter, String); Handler) method in other Wroker threads to execute onReceive method. The BroadcastReceiver#onReceive() method takes more than 10 seconds and may be killed by the system.

  6. Avoid using an implicit Intent to broadcast sensitive information that may be received by other apps registered with the BroadcastReceiver. Context#sendBroadcast() an implicit broadcast sent via Context#sendBroadcast() is received by all interested receivers. Receivers registered to listen for the broadcast may pick up sensitive information transmitted in the Intent and perform other dangerous operations. If the broadcast sent is an ordered broadcast using Context#sendOrderedBroadcast(), a malicious receiver with a higher priority may discard the broadcast directly, making the service unavailable, or stuffing malicious data into the broadcast result. If broadcastmanager #sendBroadcast() is applied only within an application, it can be implemented using LocalBroadcastManager#sendBroadcast() to avoid the risk of sensitive information leakage and Intent interception. The above broadcasts may be received by the following receivers of other applications, resulting in sensitive information leakage

  7. When adding fragments, make sure that FragmentTransaction#commit() is called within Activity#onPostResume() or FragmentActivity#onResumeFragments(). Do not use FragmentTransaction#commitAllowingStateLoss() instead, any use of commitAllowingStateLoss() must be reviewed to ensure no negative effects. An Activity can be destroyed for various reasons, and the Android support page can save its own state via Activity#onSaveInstanceState() before being destroyed. But if FragmentTransaction.com MIT () in the Activity state after save, will cause the Activity heavy build, restore state cannot restore page state, which could go wrong. In order to avoid bad to cause the user experience, system will be thrown IllegalStateExceptionStateLoss anomalies. Recommended practice is the Activity of onPostResume () or onResumeFragments () (to FragmentActivity) performed in FragmentTransaction.com MIT (), This can also be done in onCreate() if necessary. Don’t use FragmentTransaction.com mitAllowingStateLoss () or directly use try-catch avoid the crash, that is not the root of the problem solution, Do this if and only if you are sure that the commit loss will not be affected while the Activity rebuilds and restores its state.

  8. Do not free resources, such as the destruction and stop of some worker threads, inside Activity#onDestroy(), as onDestroy() may be executed late. This can be done in Activity#onPause()/onStop() with isFinishing() judgment as needed.

  9. Avoid nested fragments if you don’t have to. Note: Nested Fragment is a function added to SDK and Support library in Android API 17. When using nested Fragment, there will be some holes and bugs. Common problems are as follows:

  • The onActivityResult() method is incorrectly handled. The embedded Fragment may not receive the callback from the method and needs to be forwarded by the host Fragment.
  • Mutation animation effect;
  • Inherited setRetainInstance(), causing unnecessary lopes to be triggered multiple times during Fragment reconstruction. Avoid using nested fragments in unnecessary scenarios. Pay attention to the above problems if necessary.

10.Always start or bind a Service with an explicit Intent, and do not declare an Intent Filter for the Service to ensure application security. If you really want to use implicit invocation, you can provide an Intent Filter for the Service and exclude the component name from the Intent, but you must use the Intent#setPackage() method to specify the package name of the Intent. This fully eliminates the uncertainty of the target service.

11.Service requires multiple threads to concurrently process multiple startup requests. IntentService is recommended to avoid complex Settings. Note: Service components generally run the main thread and should avoid time-consuming operations. If there are time-consuming operations, they should be executed on the Worker thread. You can use IntentService to perform background tasks.

12.For broadcasts only used in applications, it is preferred to use LocalBroadcastManager for registration and transmission, which has better security and higher operating efficiency. Prompt for code that sends a global broadcast using Context#sendBroadcast() and other methods. If the broadcast is only used in applications, LocalBroadcastManager can be used to avoid security problems such as broadcast leakage and broadcast interception, and is more efficient than global broadcast and local broadcast.

13.The onCreate method of the next Activity is executed only after the onPause method of the current Activity is finished. Therefore, it is not suitable to do time-consuming work in the onPause method, which affects the efficiency of page-hopping.

14.Do not cache data in Android Application objects. To share data between basic components, use mechanisms such as Intent or data persistence mechanisms such as SharedPreferences.

15.When using toasts, it is recommended to define a global Toast object so that you do not have to cancel the previous Toast message when displaying a sequence of toasts (if you have a sequence of toasts, avoid toast.maketext).

16.When using Adapter, if you are using ViewHolder for caching, the getView() method does not need to set properties for each of the convertView’s child controls (for example, a TextView may set the text to NULL, A button’s background color is transparent, a control’s color is transparent, etc.), you need to explicitly set the property (Textview text is empty also need to set setText(“”), background transparency also need to set), otherwise in the process of sliding, because adapter item re-use reason, There will be content display error chaos.

17.When an Activity or Fragment registers a BroadCastReceiver dynamically, registerReceiver() and unregisterReceiver() must be paired. Note: If registerReceiver() and unregisterReceiver() are not paired, the registered receiver may not be deregistered at an appropriate time. As a result, memory leaks occur, occupying memory space, and increasing the burden on SystemService. Some Huawei models control resources on receivers. If an application registers too many Receivers, the control module will throw exceptions and the application will crash. Activity life cycles do not correspond. Multiple onResumes may occur, causing the receiver to register multiple onResumes, but only one of them is unregistered, and the remaining receivers leak memory.

4. UI and layout

  1. When you have to use ViewGroup multiple nesting in your layout, use a RelativeLayout instead of a LinearLayout to reduce the nesting count. Note: Any View on the Android application page needs to go through measure, layout, draw three steps to be correctly rendered. Measure is carried out from the top node of XML layout, and each child node needs to provide its own size to its parent node to determine the display position. During this process, measure may be re-measured (which may cause the time consumption of measure to be 2-3 times of the original). The deeper the node is, the more measures brought by nesting, and the more time it takes to compute. That’s why flat Views perform better. At the same time, the more views a page has, the longer it takes to measure, layout and draw. To shorten this time, the key is to keep the tree structure of the View as flat as possible and remove all views that do not need to be rendered. Ideally, the total measure, layout and draw time should be controlled within 16ms to ensure smooth UI when sliding the screen. To find superfluous views (views that increase rendering latency), you can use the Hierarachy Viewer tool in Android Studio Monitor to visually View all views. Multiple nesting causes time-consuming steps such as measure and layout.

  2. Use DialogFragment instead of Dialog/AlertDialog when displaying a Dialog or pop-up layer in an Activity. This helps you manage the Dialog/ pop-up layer life cycle along with the Activity life cycle.

  3. Source files are encoded in UTF-8 format.

  4. Disallow view-related operations on non-UI threads.

  5. Text size in dp, view size in dp. For Textview, wrAP_content layout is recommended if the text size is fixed to avoid the problem of incomplete text display.

  6. It is forbidden to set the same background in the child view and parent view for multiple times during layout design, resulting in excessive drawing of the page. It is recommended to hide the layout that does not need to be displayed in time.

  7. Merge and ViewStub are recommended to optimize the layout and reduce the number of UI layout levels as much as possible. FrameLayout LinearLayout and RelativeLayout are recommended.

  8. When you need to refresh components in a certain area, you are advised to use the following methods to avoid refreshing the global Layout:

  • Set the height and width of the fixed view size, such as the countdown component, etc.
  • Call view layout to modify the position, such as bullet screen components;
  • Define the refresh area by modifying the canvas position and calling invalidate(int l, int t, int r, int b).
  • Set a variable to allow requestLayout, and then override requestLayout and onSizeChanged controls to determine if the size of the control has not changed. When a requestLayout is entered, it is returned directly without calling the requestLayout method of super.
  1. PopupWindow and Dialog cannot be displayed while the Activity is not fully displayed.

10.Try not to use AnimationDrawable. It loads all images into memory at initialization. It takes up a lot of memory and cannot be freed. Android frames can be animated using AnimationDrawable, but loading all frames at once will cause an OOM exception on low-end devices. The pictures used in the animation frame should reduce memory consumption. If the picture is large, OOM will appear easily.

11.Cannot use ScrollView parcel ListView/GridView/ExpandableListVIew; This would load all the items of the ListView into memory, consuming a lot of memory and CPU to draw the surface. Note: ScrollView nested List or RecyclerView is officially prohibited. In addition to the various visual and interactive issues encountered during development, this approach also takes a significant toll on performance. UI components such as ListView have their own vertical scrolling capabilities, and there is no need to have a nested layer of ScrollViews. NestedScrollView is recommended for better UI experience and closer to Material Design.

5. Process, thread and message communication

  1. Do not pass large data between Android base components with IntEnts (Binder Transaction cache 1MB), which may result in OOM.

  2. Add process judgment to the Application’s business initialization code to ensure that only the required process is initialized. In particular, background processes reduce unnecessary business initialization.

  3. When a thread is created, it must be provided through a thread pool (AsyncTask or ThreadPoolExecutor or some other form of custom thread pool). It is not allowed to explicitly create threads in the application. Note: The advantage of using thread pools is to reduce the time spent creating and destroying threads and the overhead of system resources, eliminating the resource shortage problem. If you don’t use thread pools, you can run out of memory or “overswitch” by creating a large number of similar threads. In addition, creating anonymous threads is not convenient for subsequent resource usage analysis and will cause problems for performance analysis.

  4. Do not use Executors to create a thread pool. Use ThreadPoolExecutor to clear the running rules of the thread pool and avoid resource depletion. * If the thread pool object returns by Executors, it has the following disadvantages:

  • FixedThreadPool and SingleThreadPool: allow queue length integer. MAX_VALUE, which may cause a large number of requests to accumulate, resulting in OOM.
  • CachedThreadPool and ScheduledThreadPool: Allow Integer.MAX_VALUE to create a large number of threads, resulting in OOM.
  1. Interfaces cannot be updated in child threads. Updating interfaces must be done in the main thread. Network operations cannot be invoked in the main thread.

  2. Do not initialize the ViewStub in a non-UI thread, otherwise null will be returned.

  3. Minimize inter-process communication and pull-up behavior between different Apps. System resources are occupied and user experience is affected.

  4. When creating a thread, define a thread name that can identify its own services for performance optimization and troubleshooting.

  5. ThreadPoolExecutor sets the thread lifetime (setKeepAliveTime) to ensure that threads can be freed when idle.

  6. Sharing data using SharedPreferences between multiple processes is prohibited, although MODE_MULTI_PROCESS is available, it is not officially recommended.

11.Use Android multi-process with caution. Although multi-process can reduce the memory pressure of the main process, it may encounter the following problems:

  • Can’t completely exit all activities;
  • There will be a delay when entering the page of the new startup process for the first time (there may be a black screen or a white screen for several seconds, which is related to the theme of the new Activity);
  • In the case of multiple in-application processes, the Application is instantiated multiple times. Therefore, it is necessary to consider whether each module needs to be initialized in all processes.
  • Data sharing between multiple processes using SharedPreferences is unstable.

File and database

  1. Do not hardcode file paths at all times; use the Android file system API to access them. Note: Android applications provide internal and external storage, respectively for storing application data and user data generated by the application. You can use related apis to obtain corresponding directories and perform file operations.

  2. When using external storage, you must check the availability of external storage.

  3. When sharing files between applications, use FileProvider instead of relaxing file system permissions.

  4. SharedPreference stores only simple data types (such as int, Boolean, and String). You are advised to store complex data types in other ways, such as files and databases.

  5. Use Editor#apply() instead of Editor#commit() when SharedPreference submits data. In general, use Editor#commit() only when you need to determine the result of the commit and follow up on it. SharedPreference changes are first written to memory and then asynchronously written to disk using apply, and then directly written to disk using COMMIT. If applied frequently, apply performs better than COMMIT, and apply writes the last changes to disk. However, if you want to immediately retrieve the results of a storage operation and do other operations accordingly, use COMMIT.

  6. Database cursors must be closed after use to avoid memory leaks. Note: Cursor is a database query result set management class, when the query result set is small, memory consumption is not easily noticed. However, when the result set is large, repeated operation for a long time will lead to excessive memory consumption, requiring the developer to manually close the Cursor after the operation is completed. All kinds of exceptions may occur during the creation and use of database Cursor. No matter whether the program ends normally, it must be ensured that the Cursor is closed correctly in the end to avoid memory leakage. At the same time, if the use of Cursor involves multi-threaded scenarios, you need to ensure that the operation is synchronized.

  7. When multithreaded operations write to a database, they need to use transactions to avoid synchronization problems. Description: For Android, SQLiteOpenHelper will automatically cache SQLiteDatabase instances that have been opened. The singleton pattern of SQLiteOpenHelper should be used within a single App to ensure unique database connections. Since SQLite itself is a database-level lock, a single database operation is thread-safe (no simultaneous writes), and a transaction is an atomic operation, so an operation in a transaction is thread-safe. If multiple database connections are opened at the same time and data is written to the database through multiple threads, an exception will occur in the database, indicating that the database is locked.

  8. When writing big data to the database, use transactions or other mechanisms to improve I/O efficiency and ensure the execution speed.

  9. When executing SQL statements, use SQLiteDatabase#insert(), update(), and delete(). Do not use SQLiteDatabase#execSQL() to avoid SQL injection risks.

10.If the Data managed by ContentProvider is stored in an SQL database, you should avoid directly concatenating untrusted external data into the original SQL statement. A selection clause as an alternative parameter and a separate selection parameter array avoid SQL injection.

7. Bitmap, Drawable and animation

  1. Loading large images or loading multiple images at once should be done in an asynchronous thread. Image loading, which involves IO operations, and CPU intensive operations, is likely to cause stuttering.

  2. When using pictures in ListView, ViewPager, RecyclerView, GirdView and other components, we should do a good job in the cache of pictures, to avoid memory leakage caused by always holding pictures, and to avoid repeated creation of pictures, causing problems. It is recommended to useFresco, GlideAnd other photo galleries.

  3. PNG images are compressed using Tinypng or similar tools to reduce package size.

  4. Compress the image according to the actual display needs, rather than directly display the original image. The small screen of the phone, which displays the original image directly, does not increase the visual benefit, but it consumes a lot of valuable memory.

  5. Used pictures should be recycled in time to release valuable memory.

  6. According to different screen density, provide corresponding picture resources, so as to achieve a reasonable balance between memory consumption and display effect. If you want to save package volume, you can omit low-density images without affecting the UI effect.

  7. In the activity.onpause () or activity.onStop () callback, close the animation that the Activity is currently executing.

  8. At the end of an animation or other asynchronous task, you should consider whether the environment at the callback time still supports business processing. For example, the Activity’s onStop() function has already been executed, and the Activity actively frees resources in that function. The null pointer will crash if no judgment is made in the callback.

  9. Use inBitmap to reuse memory space and avoid creating new memory repeatedly.

10.Use ARGB_565 instead of ARGB_888 to reduce memory footprint without much visual impact. Note: android. Graphics. The Bitmap. The Config class definition about the storage style of the picture color:

  • ALPHA_8 stands for 8-bit Alpha bitmap;
  • ARGB_4444 stands for 16-bit ARGB bitmap;
  • ARGB_8888 stands for 32-bit ARGB bitmap;
  • RGB_565 stands for 16-bit RGB bitmap. The higher the bitmap number, the more color information is stored and the more realistic the image is. Most scenarios use ARGB_8888 and RGB_565, which is a solution to oom by reducing memory overhead while maintaining image quality. However, it is important to note that RGB_565 has no transparency. If the image itself needs to be transparent, RGB_565 should not be used.

11.Minimize the use of bitmaps, Try to use solid ColorDrawable, GradientDrawable, StateSelector and Shape combinations to build your drawing.

12.Use GIFs sparingly, limiting the number of GIFs allowed to play simultaneously on each page and the size of individual GIFs.

13.Instead of packaging large image resources directly to APK, consider downloading them remotely from a file repository to reduce package size.

14.According to the device performance, selectively open complex animation, to achieve an overall better performance and experience;

15.In interactions that rely heavily on the onAnimationEnd callback, such as when the animation is finished, onAnimationEnd may not be called back for various reasons. Add timeout protection or replace onAnimationEnd with postDelay.

16.When the View Animation finishes, call View.clearAnimation() to release the resources.

Eight, security

  1. When using PendingIntent, both empty intent and implicit intent are prohibited.
  • If a PendingIntent uses an empty Intent, malicious users may hijack the contents of the Intent. Do not construct PendingIntent with an empty Intent. The Intent that constructs PendingIntent must set ComponentName or Action.
  • PendingIntent enables code in another APP to run as if it were running in its own APP. PendingIntent The receiver has the same permissions as the sender when using the intent. When PendingIntent is used, the intent wrapped in PendingIntent is an implicit intent, which is vulnerable to hijacking and information leakage.
  1. Do not use constant initialization vector parameters to build IvParameterSpec. It is recommended that IV be generated randomly. Note: With fixed initialization vectors, the resulting cipher text is much more predictable and vulnerable to lexicographical attacks. Iv is mainly used to generate the first block of ciphertext to make the resulting ciphertext different (if the plaintext is the same) and to make password attacks more difficult. Besides, IV has no other use. Therefore, the random generation of IV is a very simple and effective way.

  2. Set android: allowBackup property to false to prevent ADB Backup from exporting data. AndroidManifest. XML file in order to facilitate the backup and recovery of program data in Android API level 8 after the addition of Android :allowBackup attribute value. This attribute is true by default, so when allowBackup is true, application data can be backed up and recovered using ADB Backup and ADB Restore.

  3. In the implementation of HostnameVerifier subclass, verify function is required to verify the validity of the server host name, otherwise it will cause malicious programs to bypass the host name validity with man-in-the-middle attacks. Note: During the handshake, if the hostname of the URL does not match the identifying hostname of the server, the authentication mechanism can call back to the implementation of this interface to determine whether the connection should be allowed. If the implementation inside the callback is not appropriate and all domain names are accepted by default, there is a security risk.

  4. Verify the validity of the server side certificate using the checkServerTrusted function in the X509TrustManager subclass. Note: The X509TrustManager subclass implemented does not validate the server’s certificate, which will cause untrusted certificates to bypass the certificate validation mechanism.

  5. The meta-INF directory cannot contain sensitive files such as. Apk,. Odex, and.

  6. The Receiver/Provider cannot set Android :export to true without permission control.

  7. Data stored in Sqlite or lightweight storage needs to be encrypted and decrypted when taken out.

  8. Prevents a WebView from accessing sensitive local data in file:schema mode.

10.Do not broadcast sensitive information. Use LocalBroadcast only in your application to avoid being received by other applications or restricted by setPackage.

11.Do not print sensitive information to the log. Description: In the process of APP development, in order to facilitate debugging, the log function is usually used to output information about some key processes. These information usually contains sensitive content, such as execution process, user name and password in plain text, etc., which will make it easier for attackers to understand the internal structure of the APP and facilitate cracking and attack. And even get valuable sensory information directly.

12.For internally used components, the “Android: Exported” property of the component is set to false. Description: Android applications use Intent mechanisms to pass data between components. If the application does not perform an unusual capture when retrieving empty, abnormal, or malfunctioning data using getIntent(), getAction(), and intent.getxxxExtra (), The application will Crash and become unavailable (local denial of service). A malicious application can send such null data, abnormal data, or malformed data to the victim application to cause local denial of service.

13.Make sure the Android: Debuggable property is set to false before publishing the app.

14.An Intent Scheme URL needs to be filtered. Note: If the browser supports the Intent Scheme Uri syntax, if the filtering is not appropriate, then malicious users may conduct some malicious actions through the browser JS code, such as stealing cookies. If you use the Intent. ParseUri letter number, get the Intent must strict filtering, Intent contains at least addCategory (” android. Intent. Category. BROWSABLE “), SetComponent (NULL), setSelector(NULL) three policies.

15.The key is encrypted and stored or used for encryption and decryption after being deformed. Do not hardcode the key into the code. Note: The application uses hard-coded key in the program during encryption and decryption, and the attacker can easily decrypt APP communication data by obtaining the key through decompilation.

16.Place the files that need to be dynamically loaded inside the APK or in the private directory of the application. If the application must place the loaded files in the directory that can be read and written by other applications (such as SDcard), it is recommended to perform integrity verification and whitelist for the untrusted loading sources to prevent them from being injected by malicious codes.

17.Note the use of addJavascriptInterface unless min API level >=17. API level>=17 allows javascript functions to be called with @javascriptInterface annotations, so it is not affected. For API level < 17, try not to use addJavascriptInterface, if you must use addJavascriptInterface:

  • HTTPS is used to load the URL and certificate verification is used to prevent the accessed page from being tampered.
  • Whitelist filtering and integrity check are performed on loaded urls to prevent accessed pages from being tampered with.
  • If you load native HTML, it should be built into APK, along with integrity verification of HTML pages.

18.If Android AES/DES/DESede encryption algorithm is used, do not use the default encryption mode ECB. Instead, CBC or CFB encryption mode should be specified. Note: Encryption modes ECB, CBC, CFB, OFB, etc. ECB has weak security and will generate the same ciphertext for the same inscription at different times, which is prone to dictionary attacks. CBC or CFB mode is recommended.

  • ECB: Electronic CodeBook, Electronic codebook mode
  • CBC: cipher-block chaining, which is the Cipher block chaining mode
  • CFB: Cipher feedback, ciphertext feedback mode
  • OFB: Output feedback, Output feedback mode

19.Do not use loopback to communicate sensitive information.

20.For applications that do not use File, disable File and explicitly set webView.getSettings().setallowFileAccess (false). For applications that use File, disable File and explicitly set webView.getSettings().setallowFileAccess (false). Disallow the File protocol to call JavaScript and explicitly set webView.getSettings().setjavascriptenabled (false).

21.In HTTPS communication of Android APP, the authentication policy needs to be changed to strict mode. Description: Android apps use ALLOW_ALL_HOSTNAME_VERIFIER in HTTPS communication, which allows SSL communication with all hosts, risking man-in-the-middle attacks that can result in sensitive information being hijacked and other forms of attack.

22.Windows. SetFlag (layoutparam.flag_secure) should be disabled for applications with high security requirements after Android5.0.

23.Zip is not recommended to allow.. /.. A path such as /file can be tampered with the directory structure to cause attacks. Note: When the zip package is allowed to exist “.. /” string, attackers can exploit more than one “.. “/” Change the location of the zip file during decompression. If the file already exists, it will be overwritten. If the overwritten file is so, dex, or odex, it may cause serious security problems.

24.Open the activity/service/receiver need to incoming intent to do the validity check.

25.Encryption algorithm: The insecure Hash algorithm (MD5 or SHA-1) is used to encrypt information, which may be cracked. You are advised to use a more secure Hash algorithm, such as SHA-256.

26.When a certificate authentication error occurs when the Android WebView component loads a web page, the default handling method handler.cancel() is used to stop loading the page. Description: The onReceivedSslError method of the WebViewClient class is called when a certificate error occurs when the Android WebView component loads a web page. If the method implementation calls handler.proceed() to ignore the certificate error, Is subject to the threat of man-in-the-middle attacks, which can lead to privacy breaches.

27.Direct transmission of command words or indirect processing of sensitive information or operations, avoid the use of socket implementation, use to control the access to verify identity communication.

Nine, other

  1. Do not pass large objects through Msg, it will cause memory problems.

  2. You cannot print logs using system.out.println.

  3. The Log tag cannot be “”. Note: An empty tag in a log is meaningless and is not conducive to log filtering.