Four major components in Android and their application scenarios
1. Activity life cycle Life cycle: when an object is born and when it dies, how to write code, and where to write code. Notice:
Life cycle under abnormal conditions: Resource-related system configuration changes or resources are insufficient: For example, when the screen rotates, the current Activity will be destroyed, and onSaveInstanceState will be called back before onStop to save data. When the Activity is recreated, onRestoreInstanceState will be called back after onStart. The Bundle data will be passed to onCreate (not necessarily containing data) and onRestoreInstanceState (certainly containing data). To prevent rebuilding when the screen is rotated, add the following configuration to the manifest file:
2. Fragment life cycle Normal startup
Normal Exit
3. Activity startup mode
4. Value transfer between Activity and Fragment
3. Use eventbus for communication. This method has high real-time performance and the Activity and Fragment can be completely decoupled.
5. Service There are two types of services:
The corresponding life cycle is as follows:
Notice The Service runs in the main thread by default, so if the Service needs to perform time-consuming operations (large file operations, database copying, network requests, file downloads, etc.), it should be completed in the child thread. ! The special case is: the Service is specified in the manifest file to run in another process. 6. Message passing mechanism in Android Why use Handler? Because the screen refresh rate is 60Hz, it refreshes about once every 16 milliseconds, so in order to ensure the smoothness of the UI, time-consuming operations need to be processed in the child thread, and the child thread cannot directly update the UI. Therefore, the Handler needs to send a message from the child thread to the main thread to update the UI. Let's go a little deeper here. The UI controls in Android are not thread-safe, so when multiple threads access the UI concurrently, the UI controls will be in an unpredictable state. Google does not use a lock mechanism to handle this problem because:
Therefore, Google engineers prefer to operate the UI through a single-threaded model, and developers only need to switch between different threads through Handler. Give an overview of the messaging mechanism in Android? The message mechanism in Android mainly refers to the operation mechanism of Handler. Handler is the key to thread switching, and switching between the main thread and the child thread is just a special usage scenario. The things you need to know about the message transmission mechanism include Message, Handler, Looper, and the MessageQueue object in Looper. As shown in the figure above, we can think of the entire message mechanism as a pipeline, where:
Why does creating a Handler in a child thread throw an exception? The work of Handler depends on Looper, and Looper (and message queue) belongs to a certain thread (ThreadLocal is a data storage class inside a thread, through which data can be stored in a specified thread, and other threads cannot obtain it), and other threads cannot access it. Therefore, Handler is indirectly bound to the thread. Therefore, to use Handler, it is necessary to ensure that there is a Looper object in the thread created by Handler and start the loop. Because there is no Looper in the child thread by default, an error will be reported. The correct way to use it is:
By default, Looper is created in the main thread and the message loop is started, so no error is reported: The entry point of the application is the main method of ActivityThread, in which a Looper is created and the loop method of Looper is executed to start the message loop so that the application keeps running. Can the child thread send messages to the main thread through the Handler? Yes. Sometimes, due to business needs, the main thread can send messages to the child thread. The Handler of the child thread must be created according to the above method and associated with the Looper. 7. Event delivery mechanism and custom View related Android's view tree The View mechanism in Android is mainly the display of Activity. Each Activity has a Window (the specific implementation class in the mobile phone is PhoneWindow). Under the Window is DecorView, and under DecorView are TitleVie and ContentView. ContentView is what we specify through setContentView in Activity. Event distribution mechanism ViewGroup has the following three methods for event distribution, while View only has dispatchTouchEvent and onTouchEvent.
Events are always distributed from top to bottom, that is, they first reach the Activity, then the ViewGroup, and then the child View. If no view consumes the event, the event will be passed back along the path. Among them:
Notice
Custom View Classification
View measurement-onMeasure The measurement of the View is ultimately done by setting two MeasureSpecs representing the width and height to the View through setMeasuredDimension in the onMeasure method, so you need to master MeasureSpec. MeasureSpec includes size information and mode information. Three modes of MeasureSpec:
The template code is given below:
***, copy the onMeasure method and remove the super method:
View drawing-onDraw To draw a View, you need to understand the coordinate system of the View in Android: The coordinate system of View is based on the upper left corner as the origin, the right side is the positive direction of the X axis, and the downward side is the positive direction of the Y axis. View drawing is mainly done through Android's 2D drawing mechanism in the onDraw method, which includes the Canvas and the Paint. The sample code is given below. The relevant API is not the focus of the introduction. The focus is on the save and restore methods of Canvas. After saving, the canvas can be zoomed in, out, rotated, tilted, etc. These two methods are generally used in conjunction, and the number of calls to save can be more than that of restore.
View position - onLayout The layout position is related to the replication of the onLayout method. Generally, when we customize View, we only need to complete the measurement and drawing. If it is a custom ViewGroup, what we need to do is to measure itself and control the layout position of child controls in onLayout. onLayout is a method that custom ViewGroup must implement. 8. Performance optimization Layout optimization 1. Use the include tag and reuse the same layout through the layout attribute.
2. Use the merge tag to remove similar views 3. Use ViewStub to delay loading of layouts that are not used immediately. For example, in a list page, the list is not loaded before the data is obtained, which can make the UI smoother.
4. Use RelativeLayout as much as possible, because it can greatly reduce the view hierarchy. Memory optimization Memory optimization should be considered during both app design and code writing: 1. Cherish the Service and try to keep it running only when it is in use. Try to use IntentService IntentService is actually implemented internally through threads and Handlers. When a new Intent arrives, a thread will be created to process the Intent, and it will automatically destroy itself after processing. Therefore, using IntentService can save system resources. 2. Release resources when memory is tight (for example, release resources when the UI is hidden). Override the callback method of Activity.
3. Configure a larger memory for the Application in the Manifest, but this is generally not recommended
4. Avoid wasting Bitmaps and try to adapt to screen devices. Try to use mature image loading frameworks, such as Picasso, Fresco, Glide, etc. 5. Use optimized containers, SparseArray, etc. 6. Other suggestions: Use enumeration variables as little as possible, use abstraction as little as possible, add as few classes as possible, avoid using dependency injection frameworks, use libraries with caution, use code obfuscation, consider using multiple processes when appropriate, etc. 7. Avoid memory leaks (objects that should have been recycled are not recycled). Once the memory of the app grows rapidly in a short period of time or GC is very frequent, you should consider whether it is caused by memory leaks. Analytical methods 1. Use the Memory tool in Android Monitors provided by Android Studio to view the memory usage and unused status. 2. Use the Heap tool provided by DDMS to view memory usage, or you can manually trigger GC. 3. Use a performance analysis library, such as Square's LeakCanary, which will notify you through Notification before and after a memory leak. What causes memory leaks? 1. Resource release problem: A problem with the program code. Certain resources, such as Context, Cursor, and IO stream references, are kept for a long time, and the resources cannot be released, resulting in memory leaks. 2. Object memory is too large: multiple objects that consume too much memory (such as Bitmap and XML files) are saved, causing the memory to exceed the limit. 3. Problems with the use of the static keyword: static is a keyword in Java. When it is used to modify a member variable, the variable belongs to the class rather than the instance of the class. Therefore, the life cycle of a variable modified with static is very long. If it is used to reference some instances that consume too many resources (most often Context), then you should be cautious. Solution 1. Try to avoid using static member variables to reference instances that consume too many resources, such as Context. 2. Context Try to use ApplicationContext, because the life cycle of Application Context is relatively long, and there will be no memory leak problem when referencing it. 3. Use WeakReference instead of strong reference. For example, you can use WeakReference<Context> mContextRef 4. Threads cause memory leaks: The main reason for thread memory leaks is that the thread life cycle is uncontrollable. For example, the Thread in the Activity is running, but the Activity is recreated for some reason, but the Thread will still run because the Thread will not be destroyed if the run method is not completed. Solution 1. Change the inner class of the thread to a static inner class (because the non-static inner class has a strong reference to the outer class object, while the static class does not). 2. Use weak references to save Context references within the thread. Methods and tools to check memory leaks
Performance Optimization
OOM Some common ways to avoid OOM: 1. Use as few large images as possible in App resources. When using Bitmap, be sure to scale down the image and pay attention to Bitmap recycling.
2. Release resources based on component lifecycle 3. IO streams, database query cursors, etc. should be closed promptly after use. 4. ViewHolder mode should be used in ListView to cache ConverView 5. Try to transfer (reuse) some objects when switching pages ANR Different components have different ANR occurrence times, the main thread (Activity, Service) is 5 seconds, and BroadCastReceiver is 10 seconds. There are generally three types of ANR: 1.KeyDispatchTimeout(5 seconds) The main type of key or touch event does not respond within a specific time. 2. BroadcastTimeout(10 seconds) BroadcastReceiver cannot process completion within a specific time 3. ServiceTimeout(20 seconds) There is a small probability that the service cannot be processed within a certain time. Solution: 1. The UI thread only performs UI-related operations. All time-consuming operations, such as accessing the network, Socket communication, querying a large number of SQL statements, complex logical calculations, etc., are placed in the child thread, and then the UI is updated through handler.sendMessage, runonUITread, AsyncTask, etc. 2. Ensure smooth operation of the user interface at all costs. If time-consuming operations require users to wait, a progress bar can be displayed on the interface. 3. When BroadCastReceiver needs to perform complex operations, it can start a Service in the onReceive() method to handle it. 9. Nine-cut images (.9 images), SVG images Nine Cuts Nine-point images are a special format of images used in Android development. The file name ends with ".9.png". This type of image can tell the program which part of the image can be enlarged and which part cannot be enlarged and needs to maintain the original ratio. Using nine-point images can ensure that the image is adaptive without blurring or deforming. Nine-point images are often used in dialog box background images.
SCG vector animation mechanism of android5.0
10. Common data storage methods in Android
11. Inter-process communication
The process communication method in Android is not completely inherited from Linux:
12. Common network frameworks Commonly used http frameworks and their characteristics
13. Commonly used image loading frameworks and their features and source code
Fresco caches images in Ashmem (system anonymous memory shared area)
No matter what happens, the garbage collector will not automatically recycle these Bitmaps. When the Android drawing system is rendering these images, the Android system library will extract these Bitmaps from the Ashmem heap, and when the rendering is completed, these Bitmaps will be put back to their original locations. If an extracted image needs to be drawn again, the system only needs to decode it again, which is a very fast operation. 14. What is the inter-thread communication tool used in Android development? The traditional method is to put some data in the synchronized code block, and then use callback to let another thread read it. In Android, I usually create a Looper thread, and then Handler passes the message. 1***Android new features related
16. Network request optimization Network request optimization
Security of network requests I don't know much about this, so let me tell you my idea. Using a hash algorithm, such as MD5, the data given to us by the server can be encrypted with a timestamp and other parameters to get a key. After the client retrieves the data, it generates a key based on the data and timestamp and compares it with the one given by the server. 17. New technology related RXJava: An asynchronous request library, the core is asynchronous. It uses an extended observation mode. When the observed object changes, it can be passed to the observer through events (onNext, onError, onComplete, etc.). RXJava also supports thread scheduling and switching. Users can specify the thread where the subscription occurs and the thread triggered by the observer. Retrofit: The URL and request method are specified through annotations. In fact, the underlying layer is implemented through OKHttp. |
<<: iOS data optimization: processing HTML strings
>>: The list of finalists for the first 51CTO Developer Competition has been announced
When I was surfing the Internet some time ago, I ...
Looking back at 2019, various popular IP content ...
A few days ago, Huawei's Consumer Business Gr...
Although operations personnel are responsible for...
Today we are going to talk about what kind of con...
Preface I took some time to read the source code ...
A landing page with beautiful production and conc...
User growth is an eternal topic in the Internet c...
It is hard to get a shot, and the topic is consta...
Elderly falls, a seemingly trivial matter, actual...
Affected by the cold wave March 2 Large-scale rai...
As an audio product, Himalaya has attracted a lar...
Li Ziqi became popular on YouTube. This is not cu...
Huang Jie: Quotes + Positions: The Final Battle R...
In the past two years, the Internet TV industry h...