Near the end of the year, looking back on 2019, many friends engaged in Android development still encounter a lot of difficulties, unable to achieve a breakthrough.



This article aims to summarize the following knowledge points in the hope of helping the above friends trapped in mobile development.

Therefore, the following article mainly introduces some knowledge points in Android development. This article is excerpted from Alibaba development manual.Download address. At the end of the article, there are advanced architecture technology advanced brain map, Android development interview topics, advanced architecture resources to help you learn and improve, but also save you the time to search for information on the Internet to learn, you can also share with friends around to learn together, through reading this article, you will learn the following:

Java language specification 2. Naming and using of Android resource files 3. Basic Components of Android 4. UI and Layout 5. Process, thread and message communication 6

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 state qualifier

    Such as: module_login_btn_pressed, module_tabs_icon_home_normal

  4. Anim resource names are named using lowercase words + underscores (_). The following rules apply: Module name
    Logical name

    [direction | serial number] tween animation resources: as far as possible in a generic animation name, such as module_fade_in module_fade_out, module_push_down_in + direction (animation); Frame Animation resources: module + function name + sequence number if possible. Such as: module_loading_grey_001

  5. Color resources are written to the modul_colors.xml file using the #AARRGGBB format. The naming format follows: module name
    Logical name

    color

    Such as: # 33 b5e5e5

  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 For example, 1dp
  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. The current style name is as follows:
  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 pictures (more than 1000 dimensions) Large resolution pictures are recommended to be managed in xxhdPI directory. 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. Do not use Intent + Parcelable for data communication between activities

    Way, consider EventBus alternatives, such as to avoid causing TransactionTooLargeException.Copy the code
  2. The Activity#onSaveInstanceState() method is not an Activity lifecycle method and is not guaranteed

    It's bound 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 in the Activity#onPause()/onStop()
    Copy the code
  3. A jump between activities via an implicit Intent that must pass a resolveActivity before issuing an Intent

    Check, avoid no suitable component, called ActivityNotFoundException abnormalities.Copy the code
  4. Avoid doing time-consuming operations in the Service#onStartCommand()/onBind() methods, if yes

    If necessary, IntentService or other asynchronous mechanisms should be used.Copy the code
  5. Avoid time-consuming operations in BroadcastReceiver#onReceive().

    Instead of creating a child thread inside the BroadcastReceiver, IntentService should be created to do so. Note: Since this method is executed on the main thread, the UI will not be smooth if a time-consuming operation is performed. You can use IntentService, create HandlerThread, or call Context#registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) methods, etc., in other Wroker thread to execute onReceive method. BroadcastReceiverThe #onReceive() method takes more than 10 seconds, butCan be killed by the system.Copy the code
  6. Avoid using an implicit Intent to broadcast sensitive information that might be registered with another Intent

    BroadcastReceiver Receives applications. Description: Through Context#sendBroadcast() Sends an implicit broadcast that is received by all interested receiversAn app registered to listen for the broadcast may acquire sensitive information transmitted in the Intent and perform other dangerous operations. If the broadcast is sent using Context#sendOrderedBroadcast(A malicious receiver with a higher priority may directly discard the broadcast, making the service unavailable, or stuffing malicious data into the broadcast results. LocalBroadcastManager can be used if broadcasting is limited to applications# sendBroadcast ()For now, 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 leakageCopy the code
  7. When adding a Fragment, make sure FragmentTransaction#commit() is on

    ActivityCalled within #onPostResume() or FragmentActivity#onResumeFragments().Do not use FragmentTransaction carelessly#commitAllowingStateLoss() instead, anyCommitAllowingStateLoss () must be reviewed to ensure no negative effects. The Activity can be destroyed for various reasons, Android support page is destroyed before the Activity#onSaveInstanceState() saves your own state. But if theFragmentTransaction.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.Copy the code
  8. Do not free resources within Activity#onDestroy(), such as those of worker threads

    Destroy and stop, as onDestroy() may be executed late. Can be based on actual needs in the ActivityExecute with isFinishing() judgment in #onPause()/onStop().
    Copy the code
  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:Copy the code
  • 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

    Series. Avoid using nested fragments in unnecessary scenarios. Pay attention to the above problems if necessary.Copy the code

10. Always start or bind a Service with an explicit Intent, and do not declare an Intent Filter for the Service. 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 process multiple startup requests concurrently. 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 operation 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 long work in the onPause method, which will affect 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 the last Toast message cannot be undeclared when the toasts are displayed continuously (avoid toast.maketext if you have toasts.maketext).

16. When using Adapter, if you are caching ViewHolder, use getView() regardless of whether or not each child of the convertView needs to be set to a property (for example, if the text of a TextView may be set 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, both 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.Copy the code
  2. Use DialogFragment instead of DialogFragment when displaying a dialog or floating layer in an Activity

    Dialog/AlertDialog, which makes it easy to manage the Dialog/ pop-up float life cycle along with the Activity life cycle.Copy the code
  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, it is recommended to use wrAP_content layout if the text size is determined to avoid incomplete text adaptation

    The topic.Copy the code
  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 triggering a global layout

    Refresh:Copy the code
  • 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;
  • Qualify the refresh by modifying the canvas position and calling invalidate(int l, int t, int r, int b), etc

    Area;Copy the code
  • By setting a variable to allow requestLayout and then overwriting the control’s requestLayout,

    OnSizeChanged () while entering requestLayout RequestLa that returns directly without calling super cannot display PopupWindow and Dialog when the Activity is not fully displayed.Copy the code

10. Do not use AnimationDrawable. It loads all images into memory at initialization. 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. You can’t 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 by a thread pool (AsyncTask or ThreadPoolExecutor)

    Or some other form of custom thread pool), does not allow explicit thread creation 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.Copy the code
  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:Copy the code
  • FixedThreadPool and SingleThreadPool: the allowable queue length is

    Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM;Copy the code
  • CachedThreadPool and ScheduledThreadPool: the allowable number of create threads is

    Integer.MAX_VALUE, which may create a large number of threads, resulting in OOM.Copy the code
  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. Use SharedPreferences to share data between multiple applications

    (MODE_MULTI_PROCESS), but is no longer officially recommended.Copy the code

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

  • Can’t completely exit all activities;
  • When entering the page of the new startup process for the first time, there will be a delay (black screen, white screen for several seconds, is white

    Whether the screen is black depends on the theme of the new Activity);Copy the code
  • When the Application is instantiated multiple times, you need to consider whether all modules need to be used

    Initialization in process;Copy the code
  • 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. [image upload failed…(image-87793C-1577675842233)]

    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, you should do a good job in the cache of pictures to avoid memory leakage caused by always holding pictures, and avoid creating pictures repeatedly

    Sexual energy question. It is recommended to use Fresco "(https://links.jianshu.com/go?to=https%3A%2F%2Fgithub.com%2Ffacebook%2Ffresco), [Glide] (https://links.jianshu.com/go?to=https%3A%2F%2Fgithub.com%2Fbumptech%2Fglide), and other image gallery.Copy the code
  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.Copy the code
  1. Minimize the use of Bitmap drawable and use solid ColorDrawable, GradientDrawable, StateSelector and Shape junctions

Combine the form of the construct drawing.

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

13. Large image resources should not be packaged directly to APK, but can be remotely downloaded through the file repository to reduce the package size.

14. Selectively turn on complex animation according to device performance to achieve an overall better performance and experience;

15. In interactions that rely heavily on the onAnimationEnd callback, onAnimationEnd may not be called until the animation is finished. Add timeout protection or replace onAnimationEnd with postDelay.

16. When the View Animation finishes, call View.clearAnimation() to release 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 in 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 internal components, set the “Android: Exported” property of the component 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 releasing 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 operation after deformation. Do not hardcode it 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 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, the HTML should be built into APK and complete the HTML page

    Check.Copy the code

18. When using Android AES/DES/DESede encryption algorithm, do not use the default encryption mode ECB, should specify the USE of CBC or CFB encryption mode. 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). 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 adopted to stop loading the faulty 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.Copy the code

Essential advanced resources

For programmers, to learn knowledge content, technology there are too many, not to be eliminated by the environment only to constantly improve themselves, we have always been to adapt to the environment, rather than the environment to adapt to us!

Being a programmer is easy, and being an excellent programmer requires constant learning. From junior programmer to senior programmer, from junior architect to senior architect, or to management, from technical manager to technical director, different abilities need to be mastered at each stage. If you decide your career direction early on, you can stay ahead of your peers in your work and ability to improve.

【Android advanced advanced knowledge summary 】

Share a themselves, included finishing here small make up to the above figure related technical system scores of companies such as tencent, headlines, ali, Meituan 19 years of interview questions, put together a video technology points and PDF (actually spent a lot of energy more than expected), contains the knowledge context + details, as space is limited, in the form of pictures here to show you.

There are advanced architecture technology advanced brain map, Android development interview topic information, advanced architecture information to help you learn to improve the advanced, but also save you on the Internet to search for information time to learn, can also share with friends around to learn together.

Android Architecture video +BAT Interview topics PDF+ Study notes

【Android development core knowledge notes 】

[Android advanced learning video], [full set of Android interview secrets] Click to receive:Android Architecture video +BAT Interview topics PDF+ Study notes

At this point, this has ended, if there is wrong place, welcome your suggestion and correction. Meanwhile, I look forward to your attention. Thank you for reading. Thank you!