Android interview 17 knowledge points summary

Android interview 17 knowledge points summary

Four major components in Android and their application scenarios

  • Activity: A component responsible for interacting with the user in an Android application.
  • Service: Often used to provide background services for other components or monitor the running status of other components. Often used to perform some time-consuming operations.
  • BroadcastReceiver: Used to monitor other components in the application.
  • ContentProvider: Real-time data exchange between Android applications.

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:

  1. When opening a new Activity with a transparent theme, the current Activity will not call back onStop
  2. onCreate and onDestroy are paired, onStart and onStop are paired (whether they are visible), onResume and onPause are paired (whether they are in the foreground and can interact with the user)
  3. When opening a new Activity, the relevant Log is:
  1. Main1Activity: onPause
  2.  
  3. Main2Activity: onCreate
  4.  
  5. Main2Activity: onStart
  6.  
  7. Main2Activity: onResume
  8.  
  9. MainA1ctivity: onStop

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:

  1. android:configChanges= "orientation"  

2. Fragment life cycle

Normal startup

  1. Activity: onCreate
  2.  
  3. Fragment: onAttach
  4.  
  5. Fragment: onCreate
  6.  
  7. Fragment: onCreateView
  8.  
  9. Fragment: onActivityCreated
  10.  
  11. Activity: onStart
  12.  
  13. Activity: onResume

Normal Exit

  1. Activity: onPause
  2.  
  3. Activity: onStop
  4.  
  5. Fragment: onDestroyView
  6.  
  7. Fragment: onDestroy
  8.  
  9. Fragment: onDetach
  10.  
  11. Activity: onDestroy

3. Activity startup mode

  1. standard: Every time an Activity is activated (startActivity), an Activity instance is created and placed in the task stack;
  2. singleTop: If an Activity activates itself, that is, the top of the task stack is the Activity, then it does not need to be created. In other cases, an Activity instance must be created;
  3. singleTask: If the instance of the Activity to be activated exists in the task stack, you do not need to create it. You only need to put this Activity on the top of the stack, that is, pop all Activity instances above this Activity and call their onNewIntent;
  4. singleInstance: A MainActivity instance is created in the task stack of application 1. If application 2 also wants to activate MainActivity, it does not need to be created. The two applications share the Activity instance.

4. Value transfer between Activity and Fragment

  1. After obtaining the reference of each other (forced transfer) through findFragmentByTag or getActivity, they call each other's public methods. However, this introduces the ugly code of "forced transfer". In addition, the two classes each hold a strong reference to each other, which is highly coupled and easily causes memory leaks.
  2. Pass the value through the Bundle method, such as the following code:
  1. //Set some parameters for fragment in Activity
  2.  
  3. fragment.setArguments(bundle);
  4.  
  5. //Get the method in Activity through getArguments in fragment
  6.  
  7. Bundle arguments = getArguments();

3. Use eventbus for communication. This method has high real-time performance and the Activity and Fragment can be completely decoupled.

  1. //Code in Activity
  2.  
  3. EventBus.getDefault().post( "message" );
  4.  
  5. //Code in Fragment
  6.  
  7. EventBus.getDefault().register(this);
  8.  
  9. @Subscribe
  10.  
  11. public void test(String text) {
  12.  
  13. tv_test.setText(text);
  14.  
  15. }

5. Service

There are two types of services:

  1. Local services belong to the same application and are started through startService or bound and proxy objects through bindService. If you just want to start a service to run in the background, you can directly startService. If you need to transfer values ​​or operate between each other, you should use bindService.
  2. Remote services (between different applications) are bound and proxy objects are obtained through bindService.

The corresponding life cycle is as follows:

  1. context.startService() ->onCreate()- >onStartCommand()->Service running -- call context.stopService() ->onDestroy()  
  2.  
  3. context.bindService()->onCreate()->onBind()->Service running --call>onUnbind() -> onDestroy()  

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:

  1. Introducing locks will complicate UI operations
  2. Introducing locks will reduce the efficiency of UI operation

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:

  1. MessageQueue is a conveyor belt responsible for the transmission and management of Message queues
  2. Looper is the engine of the pipeline, constantly taking messages out of the message queue and handing them over to the Handler for processing
  3. Message is every product
  4. Handler is a worker. But this analogy is not quite appropriate, because it is the Handler that sends and ultimately processes the Message.

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:

  1. handler = null ;
  2. new Thread(new Runnable() {
  3.  
  4. private Looper mLooper;
  5.  
  6. @Override
  7. public void run() {
  8. //You must call Looper's prepare method to create a Looper object for the current thread and then start the loop
  9. // The prepare method actually creates a Looper object for the ThreadLocal object
  10. //If the current thread has already created a Looper object, an error will be reported
  11. Looper.prepare ();
  12. handler = new Handler();
  13. //Get the Looper object
  14. mLooper = Looper.myLooper();
  15. //Start the message loop
  16. Looper.loop();
  17.  
  18. // Exit the Looper message loop at the appropriate time to prevent memory leaks
  19. mLooper.quit();
  20. }
  21. }).start();

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.

  1. @Override
  2. public boolean dispatchTouchEvent(MotionEvent ev) {
  3. return super.dispatchTouchEvent(ev);
  4. }
  5. @Override
  6. public boolean onInterceptTouchEvent(MotionEvent ev) {
  7. return super.onInterceptTouchEvent(ev);
  8. }
  9. @Override
  10. public boolean onTouchEvent(MotionEvent event) {
  11. return super.onTouchEvent(event);
  12. }

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:

  1. dispatchTouchEvent is the event distribution method. If the event can reach the view, it will be called first. Generally, we will not modify this method.
  2. onInterceptTouchEvent is the core method of event distribution, which indicates whether ViewGroup intercepts the event. If it returns true, it means interception. After that, ViewGroup's onTouchEvent will be called and the event will not be passed down.
  3. onTouchEvent is the first level and is called first in event distribution.
  4. The child View can request the parent element not to intercept through the requestDisallowInterceptTouchEvent method.

Notice

  1. Events are transmitted starting from Activity.dispatchTouchEvent(), and as long as they are not stopped or intercepted, they are transmitted from the top View (ViewGroup) to the bottom (child View). Child Views can process the events through onTouchEvent().
  2. The event is passed from the parent View (ViewGroup) to the child View. The ViewGroup can intercept the event through onInterceptTouchEvent() to stop it from being passed down.
  3. If the event is not stopped during the process of passing from top to bottom, and the top-level child View does not consume the event, the event will be passed back up. At this time, the parent View (ViewGroup) can consume it. If it is still not consumed, it will reach the onTouchEvent() function of the Activity.
  4. If the View does not consume ACTION_DOWN, other subsequent events will not be passed on.
  5. OnTouchListener takes precedence over onTouchEvent() in consuming events.

Custom View Classification

  1. Expand the existing View subclasses, such as overriding the onDraw method, extending new functions, etc.
  2. Customize combined controls to combine commonly used controls for easier use.
  3. Directly inheriting View to achieve full customization of View requires completing the measurement and drawing of View.
  4. To customize ViewGroup, you need to override onLayout to complete tasks such as determining the position of the child View.

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:

  1. EXACTLY mode: Exact mode, corresponding to when the user specifies match_parent or a specific size (in fact, specifying match_parent actually specifies the size as the parent container)
  2. AT_MOST mode: corresponds to the user-specified wrap_content. In this case, the size of the control only needs to be within the maximum size allowed by the parent control.
  3. UNSPECIFIED mode: The measurement mode that does not specify the size. This mode is rarely used.

The template code is given below:

  1. public class MeasureUtils {
  2. /**
  3. * Used for View measurement
  4. *
  5. * @param measureSpec
  6. * @param defaultSize
  7. * @return
  8. */
  9. public static int measureView( int measureSpec, int defaultSize) {
  10. int measureSize;
  11. //Get the size and mode specified by the user
  12. int mode = View .MeasureSpec.getMode(measureSpec);
  13. int size = View .MeasureSpec.getSize(measureSpec);
  14. //Return the size according to the mode
  15. if (mode == View .MeasureSpec.EXACTLY) {
  16. //Exact mode (specified size and match_parent) directly returns the specified size
  17. measureSize = size ;
  18. } else {
  19. //Unspecified mode, AT_MOST mode (wrap_content) requires a default size
  20. measureSize = defaultSize;
  21. if (mode == View .MeasureSpec.AT_MOST) {
  22. //In AT_MOST (wrap_content) mode, the minimum value between the measured value and the default value needs to be taken
  23. measureSize = Math. min (measureSize, defaultSize);
  24. }
  25. }
  26. return measureSize;
  27. }
  28. }

***, copy the onMeasure method and remove the super method:

  1. @Override
  2. protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
  3. setMeasuredDimension(MeasureUtils.measureView(widthMeasureSpec, 200),
  4. MeasureUtils.measureView(heightMeasureSpec, 200)
  5. );
  6. }

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.

  1. @Override
  2. protected void onDraw(Canvas canvas) {
  3. super.onDraw(canvas);
  4. Bitmap bitmap = ImageUtils.drawable2Bitmap(mDrawable);
  5. canvas.drawBitmap(bitmap, getLeft(), getTop(), mPaint);
  6. canvas.save();
  7. //Note that the rotation here refers to the rotation of the canvas
  8. canvas.rotate(90);
  9. mPaint.setColor(Color.parseColor( "#FF4081" ));
  10. mPaint.setTextSize(30);
  11. canvas.drawText( "Test" , 100, -100, mPaint);
  12. canvas.restore();
  13. }

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.

  1. <include
  2. android:id= "@+id/v_test"
  3. layout= "@layout/include_view" />

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.

  1. <ViewStub
  2. android:id= "@+id/v_stub"
  3. android:layout_width= "match_parent"
  4. android:layout_height= "wrap_content"
  5. android:layout= "@layout/view_stub" />
  6. //You need to call the inflate method manually for the layout to be displayed.
  7. stub.inflate();
  8. //setVisibility will also call the inflate method at the bottom layer
  9. //stub.setVisibility( View .VISIBLE);
  10. //After that, if you want to use the View in the ViewStub tag, just do it as usual.
  11. TextView tv_1 = (TextView) findViewById(R.id.tv_1);

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.

  1. @Override
  2. public void onLowMemory() {
  3. super.onLowMemory();
  4. }
  5. @Override
  6. public void onTrimMemory( int level ) {
  7. super.onTrimMemory( level );
  8. switch ( level ) {
  9. case TRIM_MEMORY_COMPLETE:
  10. //...
  11. break;
  12. Other cases :
  13. }
  14. }

3. Configure a larger memory for the Application in the Manifest, but this is generally not recommended

  1. android:largeHeap= "true"

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

  1. Tools officially provided by Android: Memory Monitor (when the memory occupied by the app increases rapidly in a short period of time or GC becomes frequent), Heap tool provided by DDMS (manually trigger GC)
  2. Square provides a memory leak detection tool, LeakCanary (which can automatically complete memory tracking, detection, and output results), for demonstration and appropriate explanation.

Performance Optimization

  1. To prevent overdrawing, you can turn on "Show overdrawing area" on your phone to check the overdrawing situation.
  2. Minimize rendering time, view nodes using the view tree, and perform performance analysis on nodes.
  3. Collect and analyze data through TraceView. When you have a rough location, use the Debug class provided by Android to collect data. ***You can open this .trace file through DDMS to analyze the function calls (including execution time and number of calls in specified situations)
  1. //Start data collection
  2. Debug.startMethodTracing( "test.trace" );
  3. //closure
  4. Debug.stopMethodTracing();

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.

  1. BitmapFactory.Options options = new BitmapFactory.Option ();
  2. options.inSampleSize = 2;
  3. //Options only save the image size, do not save the image to memory
  4. BitmapFactory.Options opts = new BitmapFactory.Options();
  5. opts.inSampleSize = 2;
  6. Bitmap bmp = null ;
  7. bmp = BitmapFactory.decodeResource(getResources(),
  8. mImageIds[position],opts);
  9. //Recycle
  10. bmp.recycle();

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.

  1. Parts 1 and 2 specify the stretchable part of the image. When the width and height of the dialog box are set in the actual program, parts 1 and 2 will be stretched to the required height and width, presenting the same visual effect as the design draft.
  2. Parts 3 and 4 define the content area of ​​the image. The content area defines the editable area, such as the text that needs to be wrapped in it.

SCG vector animation mechanism of android5.0

  1. The image quality will not be lost when the image is scaled down.
  2. Using XML to define graphics
  3. Adapt to different resolutions

10. Common data storage methods in Android

  1. Files (including XML, SharePreference, etc.)
  2. database
  3. Content Provider
  4. Save on the network

11. Inter-process communication

  1. What are the methods of inter-process communication in the operating system in Android?
  2. operating system:
  3. Windows: Clipboard, pipes, mailslots, etc.
  4. Linux: named pipes, shared memory, semaphores

The process communication method in Android is not completely inherited from Linux:

  1. Bundle
  2. File Sharing
  3. AIDL
  4. Messenger
  5. Content Provider
  6. Socket

12. Common network frameworks

Commonly used http frameworks and their characteristics

  1. HttpURLConnection: Before Android 2.2, HttpClient had fewer bugs, so using it was the best choice. In Android 2.3 and later, HttpURLConnection is the best choice. Its API is simple and its size is small, so it is very suitable for Android projects. The compression and caching mechanism can effectively reduce the traffic of network access, and also play a big role in improving speed and saving power. For new applications, you should prefer to use HttpURLConnection, because we will spend more time on optimizing HttpURLConnection in future work. Features: It is relatively light, flexible, and easy to expand. It has been improved after 3.0 and in 4.0, such as support for HTTPS. In 4.0, support for caching has also been added.
  2. HttpClient: efficient and stable, but the maintenance cost is high, so the Android development team is unwilling to maintain this library and instead switch to a more portable one.
  3. okHttp: okhttp is a Java HTTP+SPDY client development kit that also supports Android. Android 2.3 or above is required. Features: OKHttp is the Android version of the Http client. Very efficient, supports SPDY, connection pool, GZIP and HTTP cache. By default, OKHttp will automatically handle common network problems, such as secondary connections and SSL handshake problems. If OKHttp is integrated into your application, Retrofit will use OKHttp by default to handle other network layer requests. Starting from Android 4.4, the underlying implementation of HttpURLConnection uses okHttp.
  4. Volley: HttpClient was used in the early days, and HttpURLConnection was used later. It is a network request framework launched by Google in 2013. It is very suitable for network operations with small data volumes but frequent communications. However, for network operations with large data volumes, such as downloading files, Volley's performance will be very poor.
  5. xutils: caching network request data
  6. Retrofit: The request method is very similar to that of the Volley framework. The underlying network request uses okhttp (high efficiency, android4.4 uses okhttp at the bottom layer). Annotations are used to specify the request method and URL address, reducing the amount of code.
  7. AsyncTask

13. Commonly used image loading frameworks and their features and source code

  1. Picasso: PicassoSquare's network library can work best together, because Picasso can choose to hand over the cache part of the network request to okhttp implementation.
  2. Glide: It imitates Picasso's API and adds a lot of extensions (such as GIF support) based on it. It supports image streaming, so it is more commonly used in video applications such as sex shots.
  3. Fresco: Fresco has a module called image pipeline. It is responsible for loading images from the network, local file system, and local resources. In order to save space and CPU time as much as possible, it has a 3-level cache design (2-level memory, 1-level file). Fresco has a module called Drawees, which is convenient for displaying loading images. When the image is no longer displayed on the screen, it releases memory and space in time.

Fresco caches images in Ashmem (system anonymous memory shared area)

  1. Heap memory: The size of the Java heap memory for each app in Android is strictly limited. Each object is instantiated in the heap memory using Java's new, which is a relatively safe area in memory. The memory has a garbage collection mechanism, so when the app is not using the memory, the system will automatically reclaim this memory. Unfortunately, the process of garbage collection of memory is the problem. When the memory is garbage collected, the memory is not only garbage collected, but the Android application is completely terminated. This is also one of the most common reasons for users to freeze or temporarily freeze when using the app.
  2. Ashmem: When Android operates the Ashmem heap, it extracts the memory area containing data from the Ashmem heap instead of releasing it. This is a weak memory release mode; the extracted memory will only be released when the system really needs more memory (system memory is insufficient). When Android puts the extracted memory back into the Ashmem heap, as long as the extracted memory space is not released, the previous data will be restored to the corresponding position.

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

  1. 5.0: Material Design, support for multiple devices, support for 64-bit ART virtual machine, Project Volta battery life improvement plan, etc.
  2. 6.0: Dynamic permission management, transition animation, payment, fingerprint, etc.
  3. 7.0: split screen, quick reply to notifications, night mode, data saver mode, etc.

16. Network request optimization

Network request optimization

  1. Try to cache what can be cached to reduce the pressure on the server. For example, some data on the home page of the APP, such as the icons and text on the home page, are cached, and specifying this data through the network can make the app more flexible.
  2. No domain name is needed, just use IP to connect directly, eliminating the need for DNS domain name resolution.
  3. Connection reuse, request merging, request data Body can be compressed using the compression algorithm Gzip, and JSON is used instead of XML

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

Recommend

8 trends in brand IP marketing in 2020

Looking back at 2019, various popular IP content ...

Network framework analysis – all tricks

Preface I took some time to read the source code ...

How does “landing page” achieve user growth?

A landing page with beautiful production and conc...

A must-have user growth map for new product developers

User growth is an eternal topic in the Internet c...

Himalaya product operation analysis!

As an audio product, Himalaya has attracted a lar...

The formula for hit products created by internet celebrities!

Li Ziqi became popular on YouTube. This is not cu...

Huang Jie: Market Price + Position: The Final Battle is Over

Huang Jie: Quotes + Positions: The Final Battle R...