This question is submitted by Shuai Bi Zhang's close friend "Xueli", which gives a relatively comprehensive summary of our Android interview knowledge from small to large.Copy the code

Only used for and record their own knowledge points to see the summary, pictures from the network blog.


1. Activity and Fragment life cycles?

The Activity:

  • Start Activiy: onCreate -> onStart() -> onResume() and the Activity enters the running state.

  • The Activity retreats to the background (Home or starts a new Activity): onPause() -> onStop().

  • The Activity returns to the foreground: onRestart() -> onStart() -> onResume().

  • If the Activity is running out of memory during the background, the startup process is restarted when it is started again.

  • Lock screen: onPause() -> onStop().

  • Unlock: onStart() -> onResume().  

Fragment:

  • Create Fragment: onAttach() -> onCreate() -> onCreateView() -> onActivityCreate() -> onStart() -> onResume()

  • Destroy Fragment: onPause() -> onStop() -> onDestroyView() -> onDestroy() -> onDetach().

  • Return to the previous Fragment from the return stack: onDestroyView() -> onCreateView() -> onActivityCreated() -> onStart() -> onResume().

Activity and Fragment relationships:

2. What are the four startup modes and features of the Activity?

  • Standard: Each startup creates a new instance and puts it at the top of the stack. (You can’t start an Activity in this mode using a Context other than the Activity class. If you start an Activity, FlAG_ACTIVITY_NEW_TASK creates a stack.)

  • SingleTop: If the Activity is started at the top of the stack, it is not rebuilt and the Activity’s onNewIntent() method is called. If it is not at the top of the stack, it is standard.

  • SingleTask (in-stack reuse mode) : If the started Activity is in the stack, no new instance is created, the onNewIntent() method is called, and all activities above the Activity are cleared. (If the Activity is started by another application, a new Task is created if it does not exist. If it exists in the background, The background Task also switches to the foreground.

  • SingleInstance: A new Activity directly creates a new task stack. When an Activity in this mode exists on a stack, the instance is reused by any subsequent activation of the Activity.

3. How to cache an Activity?

When an Activity terminates abnormally, onSaveInstanceState() is called to save the state of the Activity (onStop() and onPause() have no established sequential relationship). When rebuilding, onRestoreInstanceState() is called, The onSaveInstanceState() method is also passed the Bundle object parameters saved when the Activity is destroyed to both onSaveInstanceState() and onCreate(). Therefore, the Activity state can be restored using the onRestoreInstanceState() method, which is called after onStart(). OnCreate () and onRestoreInstanceState() : The onRestoreInstanceState() callback indicates that the Bundle object is not empty. OnCreate () requires a non-null judgment. OnRestoreInstanceState () is recommended.

4. Service lifecycle and two startup methods.

  • StartService Start a service: Used to start a service to perform background tasks. StopService () is used to stop the service.

  • BindService Starts the service: starts the service for communication and stops the service using unbindService().

  • StartService/stopService onCreate() -> onStartCommand() -> onDestroy() the first call triggers onCreate() and onStartCommand, After that, only onStartCommand() is triggered each time the service is started. No matter how many times startService is started, stopService will stop the service once

  • BindService/unbindService onCreate () – > onBind () – > onUnbind () – > onDestroy () for the first time bindService will trigger the onCreate () or onBind (), Each subsequent bindService does not trigger any callbacks. The bindService startup lifecycle is attached to the Context in which it was started

5.

  • Set the return value to START_STICKY in onStartCommond()

  • Restart the service in onDestroy()

  • Black preservation: Different app processes use broadcasts to evoke each other.

  • White: Start foreground Service

  • Grey Protection: Start foreground Service using system vulnerability.

6. What is the difference between the two methods of broadcasting registration?

  • Dynamic registration: Registration is done by calling context.registerReceiver (), which listens for broadcasts at specific times, following the life cycle of the component.

  • Static registration: declare in AndroidMainfest.xml that the program will still be called after closing, resident broadcast, and always listen for broadcast.

7. How the Intent is used and the data type to be delivered.

  • Displays the Intent: specifies the component to start by name

  • Implicit Intent: Declares a general action to be performed without specifying a specific component, allowing components in other applications to handle it.

  • The Intent can also pass Parcelable and Serializable data, as well as their array/list data.

8. Use of ContentProvider.

Carry on cross-process communication, realize the data interaction and sharing between processes. Context getContentResolver() to get the instance, using Uri matching to add, delete, change, and query data. A ContentProvider uses tables to organize the data. No matter what the source of the data is, the ContentProvider considers it a table and organizes the data into tables. Right

9. Usage scenarios and features of Thread, AsyncTask, and IntentService.

  • A Thread that runs independently of an Activity. If the Activity does not stop after finish, the Thread or run method will continue to execute.

  • AsyncTask encapsulates two thread pools and a Handler (SerialExecutor for queuing, THREAD_POOL_EXECUTOR for the actual executing task, and Handler to switch the worker thread to the main thread) that must be created in the UI thread. The execute method must be executed in the UI thread. A task instance can only be executed once. Executing multiple times throws an exception for network requests or simple data processing.

  • IntentService: Handles asynchronous requests and implements multiple threads. Time-consuming operations are handled in onHandleIntent. Multiple time-consuming tasks are executed one by one and end automatically after completion.

10. Five layouts: FrameLayout, LinearLayout, AbsoluteLayout, RelativeLayout, table Elayout, their respective characteristics and drawing efficiency comparison.

  • FrameLayout: The simplest layout in Android. All controls appear in the top left corner by default. You can use properties such as layout_margin and layout_gravity to control the relative layout position of the child controls.

  • LinearLayout: a row or a column layout space, can use orientation = horizontal | vertical to control layout.

  • AbsoluteLayout: Custom space x, Y to adjust position.

  • RelativeLayout: a RelativeLayout that defines the position of a space with related properties

android:layout_centerInParent = “true | false”android:layout_centerHorizonta = “true | false”android:layout_alignParentRight = “true | false”

  • TableLayout: Layouts the positions of word elements in a table form.

11. Android data storage form.

  • SQLite database storage

  • File storage

  • SharedPreference storage

  • Network storage

12. Basic operations of SQlite

Android provides the SQLiteOpenHelper class, which makes it easy to control the creation and upgrade of databases.

  • OnCreate () : Creates the database

  • OnUpgrade () : updates the database

Both methods must be overridden and then implemented to create and upgrade the database logic.

  • GetReadableDatabase () and getWritableDatabase () : Create or open an existing database and return an object that can be read and written to the database. When the database cannot be written to, getReadableDatabase() returns a read-only database object. GetWritableDatabase () returns an exception.

  • Insert (): inserts data

  • Update (): Updates data

  • Delete (): deletes data

  • Query (): Queries data

MVC pattern in Android.

  • Model = Model

  • View

  • Controler

The View sends instructions to the Controller, which notifies the Model to change state when it completes its logic, and the Model updates the new data to the View. All communication is one-way. When receiving an instruction, one is to receive the instruction through the View and pass it to the Controller; The other is to receive instructions directly through the Controller.

14. Merge, ViewStub functions.

  • Merge: Reduces view levels. You can delete unnecessary levels to optimize the UI.

  • ViewStub: Loads on demand to reduce memory usage and speed up rendering. The Merge tag is not supported

15. What are the advantages and disadvantages of Json?

advantages

  • Lightweight data interchange format

  • Easier to read and write

  • Easy machine parsing and generation

disadvantages

  • Less semantic and less intuitive than XML

16. What are the two types of animation and what are their characteristics?

  • Traditional animation: frame animation and tween animation.

  • Property animation.

The difference between

  • Property animation is the real realization of view movement, tween animation to view movement is more like drawing a shadow in a different place, the actual object is still in the original place.

  • When the repeatCount of the animation is set to infinite, if the animation is not stopped when the Activity exits, the property animation will cause the Activity to be unable to be released, resulting in a memory leak, whereas the tween animation is fine.

  • XML file tween animation, reuse rate is very high. In the Activity switch, window popup and other scenarios have a good effect.

  • When using frame animation, be careful not to use too many extremely large images, which can lead to insufficient memory.

17. Handler, Loop message queue model, function of each part.

The Android Message mechanism includes MessageQuene, Handler, Looper, and Message.

  • Message: need the Message of Spring birthtree, can transfer data.

  • MessageQuene: Message queue, which maintains a list of messages through a singly linked list data structure (post and delete messages).

  • Handler: Message helper class that sends various message events to the message pool

Handler.sendMessage Sends messages handler. handleMessage processes messages

  • Looper: Continuously reads messages from the message queue and distributes them to the target handler according to the distribution mechanism.

The relationship between MessageQuene, Handler, and Looper:

Only one Looper can exist per thread, stored in ThreadLocal. The main thread (UI thread) has already created a Looper, so there is no need to create a Looper in the main thread; loopers need to be created in other threads. There can be multiple handlers per thread, meaning that a Looper can handle messages from multiple handlers. A MessageQueue is maintained in Looper to maintain Message queues, where messages can come from different handlers.

When handler.sendMessage() is called to send a message, it is actually sent to the MessageQuene bound to the current thread, and the current thread bound Looper keeps fetching new messages from the MessageQueue, Call MSG. Target. DisspatchMessage (MSG) method to bind Message distributed to the Message handler. HandleMessage ().

18. How to exit and terminate the App.

  • Create a collection class to manage all activities, ActivityCollector, with a list to manage activities.

  • KillProcess (Android.os.process.mypid ()) Kills the current program Process.

19. Differences between the Asset directory and the RES directory.

  • Assets: no tags are generated in the R file. Assets stored here will be put into the program installation package when packaged. (Access these files through the AssetManager class)

  • Res: Id tags are generated in R files. If resources are used during packaging, they are packed into the installation package. If resources are not used, they are not added to the installation package.

Res/RAW: Stores animation resources in the same way as asset files.

Tables assets res/raw res/drawable
Obtaining Resources File path + file name R.raw.xxx R.drawable.xxx
Compressed or not NO NO YES(Distortion compression)
Whether to obtain resources in subdirectories YES NO NO

20. How does Android speed up the Activity?

  1. No time-consuming operations are performed in onCreate()

  • Break down the View of the page and place it in AsyncTask step by step, preferably with a Handler. So the user see is a hierarchical step by step View display, is not to see a black screen, and then show all the View.

  • It is better to make animation, the effect is more natural.

  • The goal with multithreading is to minimize onCreate() and onReume() time so that the user can see and manipulate the page as quickly as possible.

  1. Reduce main thread blocking time

  2. Improve the efficiency of Adapter and AdapterView

  3. Optimize layout file

21. Android performance optimization method

  1. Layout optimization: Minimize the hierarchy of layout files

  • Remove useless controls and layers from the layout and selectively use lower-performance viewgroups

  • With tags, viewStubs, and layout reuse, the hierarchy of the layout can be reduced. (The ViewStub provides the ability to load the layout on demand, and only loads the layout into memory when needed, improving the initialization efficiency.)

  • Avoid overdrawing

  1. Draw optimization: View’s onDraw() method avoids doing a lot of work.

  • Do not create new layout objects in onDraw().

  • OnDraw () does not do time-consuming tasks, a large number of loops occupy the CPU time slice, resulting in a smooth View drawing.

  1. Memory leak optimization

  • Avoid writing memory leaking code

  • Use analysis tools (MAT, LeakCannary) to find out potential memory leaks and fix them.

Causes of memory leaks:

  1. Leakage of collection classes

  2. Singleton/static variables cause memory leaks

  3. Anonymous inner classes/non-static inner classes cause memory leaks

  4. Resources are not closed

  1. Response speed optimization: Avoid time-consuming operations on the main thread.

  2. ListView/RecyclerView optimization:

  1. Use the ViewHolder pattern for efficiency

  2. Asynchronous loading: Time-consuming operations are placed on asynchronous threads

  3. Stop loading and pagination loading when sliding

  1. Thread optimization: Use Thread pools to avoid large numbers of threads in applications.

  2. Other performance optimizations:

  1. Don’t create too many objects.

  2. Don’t use enumerations too much; they take up more memory than integers.

  3. Constants use static final modifications.

  4. Use android-specific data structures.

  5. Use soft and weak references appropriately.

  6. Memory cache and disk cache are used.

  7. Use static inner classes whenever possible to avoid potential memory leaks due to inner classes.

22. Application scenarios of soft and weak references in Android.

Java reference type classification: In the development of Android applications, in order to prevent memory overflow, soft reference and weak reference technology can be applied as far as possible when dealing with some objects that occupy large memory and have a long declaration cycle.

Soft/weak references can be used in conjunction with a ReferenceQueue (ReferenceQueue), and if the object referenced by the soft reference is collected by the garbage collector, the Java virtual machine adds the soft reference to the ReferenceQueue associated with it. Using this queue, you can get a list of objects with soft/weak references that have been reclaimed, thus clearing invalid soft/weak references for the buffer.

If you just want to avoid OOM exceptions, use soft references. If you are more concerned about the performance of your application and want to reclaim some memory-consuming objects as quickly as possible, you can use weak references.

You can choose soft or weak references based on how often the object is used. If the object is likely to be used frequently, use soft references. If it is more likely that the object will not be used, use weak references.

23. Bitmap compression strategy

  1. How to load Bitmap:

  • Four classes of BitmapFactory methods:

  • DecodeFile (file system)

  • DecodeResourece (resources)

  • DecodeStream (Input stream)

  • DecodeByteArray (number of bytes)

  1. BitmapFactory opeions parameters

  • InSampleSize Sampling rate that scales the height and width of the image to the smallest ratio (usually an exponent of 2). The width and height scaling ratios are usually calculated according to the actual width and height of the image/the required width and height. However, the smallest zoom ratio should be taken to avoid that the zoom picture is too small and cannot be spread all over the specified control, which needs to be stretched to cause blur.

  • InJustDecodeBounds gets information about the width and height of the image, which is given to inSampleSize to select the zoom ratio. InJustDecodeBounds = true and then loading the image can parse only the width and height of the image without actually loading the image, so this operation is lightweight. After obtaining the width and height information, calculate the zoom ratio and reload the image with inJustDecodeBounds = false to load the scaled image.

  1. Efficient process for loading bitmaps

  • Set bitmapFactory. Options to True and load the image

  • Extract the image’s original width and height information from bitmapFactory. Options, corresponding to the outWidth and outHeight parameters

  • Calculate the sampling rate inSampleSize according to the sampling rate rule and the size of the target view

  • Set BitmapFactory.Options to False to reload the image

24. Custom View process: onMeasure(), onLayout(), onDraw()

  • OnMeasure () method: a single View. This method is overridden to specify the default size of the View for wrap_ content to avoid matching the size of match_parent. ViewGroup, if we don’t rewrite it, we’re going to do the same logic that we did in monad views, we’re not going to measure the child views. The onMeasure() method is overridden and the subview is cycled.

  • OnLayout () method: single View, no need to implement this method. The ViewGroup has to be implemented, and this method is an abstract method that you implement to lay out the child views.

  • OnDraw () method: Either a single View or a ViewGroup needs to implement this method because it is an empty method.

25. Event distribution mechanism

Detailed description of event distribution mechanism

Android long connection, how to deal with heartbeat mechanism.

  • Long connection: The long connection is not automatically disconnected after the connection is established. Both parties send data to each other, do not actively disconnect after sending data, and then continue to send data through the connection.

  • Heartbeat packet: To prevent NAT timeout, the client sends a packet to detect whether the connection is down

  • The server processes heartbeat packets: if the heartbeat interval of the client is fixed, the server considers that the other party is disconnected and closes the connection when the connection is idle for more than this time and no heartbeat is received. If the heartbeat rate of the client changes dynamically, set a maximum value. If the value exceeds the maximum value, the client is considered to be disconnected. In another case, the write timeout occurs when the server sends messages to the client through the TCP connection, and the client is directly considered disconnected.

  • Android wechat intelligent heartbeat solution

27. Zygote startup process

In Android, zygote is the name of a process. Android is based on the Linux System, and when your phone is turned on and the Linux kernel is loaded, a process called “init” starts. In Linux, all processes are forked by the init process, and zygote is no exception.

28. Android IPC:Binder principle

  • IPC: Processes are not shareable with each other, whereas kernel space is shareable. The Client process communicates with the Server process and uses the shared kernel memory space between processes to complete the underlying communication work. The Client and Server processes often use iocTL and other methods to interact with the driver of the kernel space.

  • Binder principle:Binder communication uses the C/S architecture and consists of Client, Server, ServiceManager, and Binder drivers. The ServiceManager manages various services in the system. The architecture diagram is as follows:

Four roles of Binder:

  1. Client process: processes that use services

  2. Server process: a process that provides services

  3. The ServiceManager process converts character type Binder names into references to the Binder names in the Client so that the Client can obtain references to the Binder entities in the Server.

  4. Binder driver: a series of low-level support for inter-process communication, inter-process delivery of Binder, Binder reference count management, inter-process delivery and interaction of packets.

Binder operating mechanism:

  1. Register services: The Server registers services with the ServiceManager

  2. Obtaining services: The Client obtains services from the ServiceManager

  3. Using a Service: The Client establishes a communication channel with the Server process based on the obtained Service information and interacts with the Server.

29. New features for Android 5.0, 6.0, 7.0 8.0.

  • 5.0:

  1. Material Design

  2. Support for multiple devices

  3. New Notification Centre

  4. Supports 64-bit ART VMS

  5. Battery life improved

  6. New “Recent Apps”

  7. Safety improvement

  8. Different data are saved independently

  9. To improve the search

  10. Support bluetooth 4.1, USB Audio, multi-party sharing, etc

  • 6.0:

  1. Dynamic Rights Management

  2. The system layer supports fingerprint identification

  3. APP associated

  4. Android Pay

  5. Power management

  6. TF card is stored by default

  • 7.0:

  1. Split screen multitasking

  2. Drop down shortcut switch

  3. New notification message

  4. Night mode

  5. Traffic protection mode

  6. New Settings

  7. Improved Doze sleep mechanism

  8. System-level phone blacklist

  9. Menu key quick switch app

  • 8.0:

  1. Picture in picture

  2. Notify the logo

  3. Self-filling frame

  4. System optimization

  5. Background restrictions

  6. Many more optimizations for Android 8.0


Welcome to follow nanchen’s official account: Nanchen if you like, you can choose to share with everyone. If you have a good article, welcome to contribute, praise all belong to you.

If you happen to be joining us

Stormzhang’s Planet of Knowledge

Scan the QR code below to join

Long press the qr code above to pay attention

Do not finish the open source, write not finish hypocritical

Nanchen’s growing notes