This article is intended for two types of students: 1. Students preparing for Android developer job interviews. 2. Students who want to learn the mechanism of Android system quickly. First of all, if you’re a large company, it’s more about your knowledge of Android than it is about project experience.

“The average student at a training school can write code within a few months, so what’s your advantage?”

Yes, our strength is our deep understanding of the mechanics of the Android system. Without further ado, let’s begin.

First, the underlying research of Android system

The knowledge point about the bottom layer is not in an article can explain clearly, see my Android bottom research series, constantly updated.

Second, Android important knowledge

The following selected more common knowledge points, determined to put an end to a simple list of answers, because that can not understand also remember. So try to express it in a simple and progressive way. Patience is sure to help you with most interview questions.

Read what you are familiar with first, and then move on to the less familiar.Copy the code

1. Start mode of Activity

What is starting an Activity?Copy the code

Typically, you create an Activity object and put the Activity into a Task stack for management (switching, shutting down, etc.). So the question is, if I already have this Activity object in the stack, do I need to create a new object? Android offers four options:

  • Create a new activity at the top of the stack regardless of whether it’s there or not:Standard model
  • If the activity I want to open is right at the top of the stack, I just use it; Otherwise create a new one:SingleTop mode
  • This is a bit overbearing. That is, if an activity is already on the stack, when you want to start it, even if there are other activities on top of the stack, they are removed to the top of the stack. If not, create one. :SingleTask mode
  • This one is even more overbearing. When you start the activity, you create a stack and add the activity to the new stack instead of trying to squeeze it into another stack. When you want to start the activity again, jump directly to the new stack. :SingleInstance mode(that is, only one instance is created and placed in a separate task stack to be shared by other task stacks)



Boot mode

2. Activity (or component) communication mechanism

When do activities (components) need to communicate?Copy the code

Communication mechanisms are typically involved when data needs to be passed from one Activity (component) to another. For example, start a new Activity and pass data to it.

How to communicate/transfer data?Copy the code

The most commonly used messenger of Android is Intent. An Intent is an Intent that takes data to deliver and then sets off to a specified destination. So the question is, what if you bring all kinds of data? How do you navigate to your destination?

How to bring all kinds of data?Copy the code

Just like sending a letter, you can’t just shove a messy pile of paper into a messenger and have it delivered. You can just wrap the letter in an envelope. The same thing happens in Android, where you package the data and then you give it to messenger, which is the bundle. Yeah, we put a bunch of messy data in a bundle, and then we give the bundle to the Intent.

How do you navigate to your destination?Copy the code

If you want to post something, there are two ways: 1. Write a full address on the envelope; 2, if you want to mail useless quilt books to the disaster area, but you do not care to send to which disaster area, you can write to help me casually sent to a disaster area, and then the post office administrator will be nationwide query, if found the disaster area such as Wenchuan, it will be mailed to that. The same goes for Android, where explicit Intent and implicit Intent specify a specific component name, such as the target activity. The latter does not specify a name and only gives a description (intent-filter). Android then searches based on that description.

One problem with data packaging, however, is that if you’re passing normal data you can put it directly into the bundle, but if you’re passing objects.

How to package and pass objects in bundles! ?Copy the code

Object serialization mechanism

As we already know, when communicating between components, we use the bundle to package the data and then deliver it to the messenger intent. So the question is, right?

How does the bundle package the data?Copy the code

Here we divide the data into two types, one is the prototype data, such as int, string, etc., can be packaged and passed directly. The packing method is as follows:

bundle.putInt("key1", 20);
bundle.putString("key2", "hello");Copy the code

The other type is Java objects, which are not directly given to the bundle. Instead, they are serialized and then given to the bundle. The object is then transferred as a binary stream until the target component receives the Bundle and deserializes the binary data of the object to obtain the real object.

So how do you serialize an object?Copy the code

Two ways.

  • Java language-based Serializable method: The object class implements the Serializable interface;
  • Parcel serialization based on Android: Implement the Parcelable interface. As long as the class implements these two interfaces, objects can be stored in the bundle:
bundle.putSerializable(Key, Object);
bundle.putParcelable(Key, Object);Copy the code

then

What is the difference between these two mechanisms?Copy the code
  • The Serialize mechanism in JAVA converts an object into a byte streamstorageIn the external equipment, inNeed to bewhenTo regenerate theObject (usingJava reflectionMechanism). It is used to store object status on external devices and transfer objects over networks. The downside is that there are a lot of intermediate objects and some GC(garbage collection), in a nutshellSerialize more slowly;
  • The Android offer Parcel mechanism is aimed atMobile devicestheLightweight and efficientObject serialization mechanism. The entire process is in memory, no external devices are involved, and deserialization reads the original object rather than creating a new one. In simple termsParcel faster; But itUsing complex.

So if you serialize an object and you put it in a bundle and you deliver it to another component in the intent,

Why does an object need to be serialized before it can be passed between components via an Intent? ?Copy the code

Take startActivity(Intent) as an example. This function starts Activity B from Activity A and packages the data to the intent and passes it to Activity B. That is, if the data in the Intent contains a Java object, the object must be serialized before it can be passed to B. In the process of starting B Activity, you need to leave the process where the application is running and call the native method to enter the Linux kernel process to perform the actual operation of switching activities. When done, the transfer data is brought back into the application process and the raw packaged data is parsed. In other words, when B Activity is started, the packaged data goes through a different process: Java objects cannot be transferred directly between processes (see below), so we need to serialize Java objects in advance to make them viable for later cross-process transfers.

4. Inter-process communication mechanism IPC

What is a process?Copy the code

Simply put, a process often represents an application. The operating system allocates a certain amount of memory and other resources to each process, and the process runs in this memory.

What is interprocess communication?Copy the code

Generally speaking, for security purposes, the memory space acquired by a process is an abstract piece of memory, which is then mapped to a physical piece of memory, so that no process can access the data in the memory of the other process. For example, if qq and a bank client are opened on the mobile phone, the operating system will create two independent memory areas for them to run, and QQ process is unable to access the bank client data, which ensures the security of data. The drawback, however, is that data cannot be transferred directly between processes, so a unique interprocess communication mechanism has to be introduced.

Can objects be passed directly between processes?Copy the code

As you know, interprocess communication means passing data between two different pieces of physical memory. First, native data such as int String data can be passed, as long as you specify the type of the data, then it can be restored in the target process. But object data, if passed directly to the object, cannot be recovered by the target process, and therefore cannot be recognized.




Memory area data communication

Diagram of communication between different applications in Android system. A process represents an application.Copy the code



Interprocess communication

Additional: An important part of the IPC mechanism is the Binder mechanism, which is used to deliver between different processes. This part of the interview is usually not too difficult to ask. At present I am still sorting out this part of the content, continue to update.Copy the code

5. Multi-threaded management

Interprocess communication was mentioned earlier, so let’s talk about multi-threaded management in Android, and we’ll talk about interthread communication later. First of all, the basic concept of threads is not explained here, as long as it is understood that threads are lightweight processes that perform actual operations in a limited amount of process memory.

What are Main threads and Worker threads?Copy the code

When the application is started, it automatically creates a Main Thread, also known as the UI Thread. The Main function is to draw the UI interface and interact with the user. Threads other than the main Thread are called child threads or Worker threads. These threads are often used to perform time-consuming operations such as network communication or database access. If a time-consuming operation is performed on the main thread, the interface cannot be drawn or user operations cannot be responded to during the execution. In the eyes of users, the operation is delayed, which may cause ANR and damage the user experience.

The main thread is thread unsafeCopy the code

Many places on the web explain thread-safety not as a cause, but as a result, i.e. UI controls can only operate in the main thread and not in other threads, otherwise multiple threads working on the same control will fail. This explanation does not explain why the main thread is not thread safe, but rather makes it seem like The Android system has restricted UI elements to the main thread, which is easy to misinterpret as safe. My explanation is that you can actually code UI elements in child threads and crash them. Assuming that the main thread is safe, the safe situation is that we don’t have to worry about accidentally manipulating the UI in the child thread because the system will block that. In fact, the system does not shield it, and any time a developer manipulates UI elements in a child thread, it is likely to crash. That’s why we say that the main thread in Android is not secure.

Additional knowledge: What is thread-safe/unsafe? In multithreaded environments, it is common for a piece of code to be executed separately by multiple threads. It is common for one thread to execute part of the code and then another thread to execute the code and modify the variables. When the original thread comes back to run again, the variable inside has been changed by someone else but it doesn't know about it, and it ends up with an error. Such threads are not safe. When a safe thread executes a piece of code, no other thread can execute the code or modify variables until it finishes executing.Copy the code

then

How do threads communicate with each other?Copy the code

Handler, Looper, and MessageQueue are described in detail in my other article. In simple terms, each thread has these three things. For example, if thread A wants to send A message to thread B, The handler of thread B is called in thread A to send messages. The messages are automatically sent to the message queue of thread B. Meanwhile, the Looper of thread B continuously traverses the queue and automatically processes new messages if it finds them.

FAQ:

How to avoid ANR(Application Not Response)?Copy the code

Try to execute time-consuming operations (such as network requests or database reads) or costly operations in the child thread. When the child thread finishes executing, use handler to notify the main thread to make updates.

6. Memory management mechanism

As mentioned earlier, each application runs in a separate process (actually a separate Dalvik process) and the system allocates fixed memory to it. Memory leaks and OOM (OOM) leaks are common in memory usage, and are severe enough to cause a program to crash. Therefore, reasonable and effective memory management is very important. Detailed management (including interview focus: image caching mechanism) can refer to my other article: Android memory management and optimization

I will not repeat it here.

Here are just three ideas for image caching:

  • LRU algorithm: set the maximum number of cached images, when the number of images exceeds the maximum, delete the less used images, so as to optimize the memory.
  • FTU algorithm: set the image cache time limit, from the last use, when the time limit will be deleted.
  • FMU algorithm: set a fixed size of cache space, when the space limit is reached, delete the maximum size of the picture.

7. Next Step:

The article continues to be updated, readers interested in the topic can reply in the comments! Thank you very much!