Home >Web Front-end >Front-end Q&A >A compilation of problems encountered by Android developers in interviews with Alibaba and other major manufacturers
Recommendation: "2020 Android Interview Questions Summary [Collection]"
Let me briefly talk about my past four years. interview experience. I interviewed with many companies, and some of them made me excited, and some made me feel disappointed and helpless. I recorded all these experiences. After thinking about it carefully, it was worth it. After interviewing so many companies, if there is nothing in the end It would be such a waste to stay. At least for me, some things can only be answered with a definite answer after sorting out and summarizing. I hope this can be of some help to you who are about to change jobs or plan to look at opportunities.
The answers to the following questions are compiled through my own interviews over the past four years. If you have any different opinions, please feel free to correct me.
Answer:
Generally, when a non-static inner class holds a reference to an external class , causing the external class to be unable to be reclaimed by the system after use, thus causing a memory leak. In order to avoid this problem, we can declare the customized Handler as a static inner class, and then let the Handler hold a reference to the external class through a weak reference, thus avoiding memory leaks.
The following is the code implementation
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private TextView mTextView; private WeakReference<MainActivity> activityWeakReference; private MyHandler myHandler; static class MyHandler extends Handler { private MainActivity activity; MyHandler(WeakReference<MainActivity> ref) { this.activity = ref.get(); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: //需要做判空操作 if (activity != null) { activity.mTextView.setText("new Value"); } break; default: Log.i(TAG, "handleMessage: default "); break; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //在onCreate中初始化 activityWeakReference = new WeakReference<MainActivity>(this); myHandler = new MyHandler(activityWeakReference); myHandler.sendEmptyMessage(1); mTextView = (TextView) findViewById(R.id.tv_test); } }复制代码
Reference blog post blog.csdn.net/ucxiii/arti…
Analysis:
When developing Android applications, it is very simple to start another Activity from one Activity and pass some data to the new Activity, but when you need to let the Activity running in the background return There may be a slight problem with going to the front desk and passing some data.
First of all, by default, when you start an Activity through Intent, even if there is already an identical running Activity, the system will create a new Activity instance and display it. In order to prevent the Activity from being instantiated multiple times, we need to configure the loading mode (launchMode) of the activity in AndroidManifest. To an Activity, if the system already has an instance, the system will send the request to this instance, but at this time, the system will not call the onCreate method that usually handles the request data, but will call the onNewIntent method
Answer:Premise: ActivityA has been started and is in the Activity stack of the current application; When ActivityA's LaunchMode is SingleTop, if ActivityA is on the top of the stack and you want to start ActivityA again, the onNewIntent() method will be called. When ActivityA's LaunchMode is SingleInstance, SingleTask, if ActivityA is already in the stack, then the onNewIntent() method will be called at this time
When ActivityA's LaunchMode is Standard, since each time ActivityA is started, a new The instance has nothing to do with the original startup, so the onNewIntent method of the original ActivityA will not be called. The onCreate method is still called.
The following is a code example
1. Set the startup of MainActivity The mode is SingleTask (reuse within stack)6b4b8de82f5ec1f2a7986e15ef3b7143
abedf4926b16e78349669730db0843a2复制代码
<activity
android:name=".MainActivity"android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>复制代码
package code.xzy.com.handlerdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.forward_btn);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
@Override
protected void onNewIntent(Intent intent) {
Toast.makeText(this, "onnewIntent", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onNewIntent: i done....");
}
}复制代码
Print screenshot
**Here is a complete set of systematic high-level architecture videos;**Seven mainstream technology modules, video source code Notes (
There is a special special package of detailed interview materials to share at the end of the article)3. What are the advantages of RecyclerView compared to ListView
Analysis:First of all, we need to explain the name of RecyclerView. Judging from its class name, the meaning of RecyclerView is that I only care about Recycler View, which means that RecyclerView only recycles and reuses Views. You can set the others by yourself. It can be seen that its high degree of decoupling gives you full freedom of customization (so you can easily achieve ListView, GirdView, waterfall flow and other effects through this control)
Secondly, RecyclerView provides the ability to add and delete items. Animation effects, and can be customized
The advantage of RecyclerView compared to ListView is that it can easily realize:
Function of ListViewOf course, you can also provide callbacks yourself through the adapter
Referencejcodecraeer.com/a/anzhuokai…
blog.csdn.net/lmj62356579…
www.360doc.com/content/16/… Answer: Proguard technology It has the following functions: Compression--check and remove useless classes in the code
Optimization--Optimize bytecode and remove useless bytecode
Obfuscation - obfuscate the name of the definition to avoid decompilation Pre-monitoring--detect the processed code again on the java platform Code obfuscation is only used when going online, debug It will be turned off in mode and is an optional technology. So why use code obfuscation? Because Java is a cross-platform interpreted development language, and the source code of java will be compiled into bytes Code files are stored in .class files. Due to cross-platform needs, Java bytecode contains a lot of source code information, such as variable names, method names, etc. And access variables and methods through these names. Many of these variables are meaningless, but they are easy to decompile into Java source code. In order to prevent this phenomenon, we need to use proguard to obfuscate the Java bytecode. Obfuscation is to reorganize and process the released program so that the processed code has the same function and different code display as the pre-processed code. Even if it is decompiled, it is difficult to understand the meaning of the code and which ones have been obfuscated. The code can still be executed according to the previous logic and get the same result. However, some java classes cannot be confused. For example, java classes that implement serialization cannot be confused, otherwise problems will occur during deserialization. When obfuscating the following code, you should pay attention to retain it and not obfuscate it. Other Anroid official recommendations are not confusing, such as The solution is that for time-consuming operations, such as accessing the network, accessing the database, etc., it is necessary to open a sub-thread and process the time-consuming operations in the sub-thread. The main thread mainly implements UI operations 6. The process of SSL certificate authentication in HTTPS First create a Handler object in the main thread and rewrite it handleMessage() method. Then when the UI needs to be updated in the child thread, we create a Message object and send the message through the handler. After that, the message is added to the MessageQueue queue to wait for processing. The Looper object will always try to retrieve the pending message from the Message Queue, and finally distribute it to the handler Message() method of the Handler. Reference blog.csdn.net/u012827296/… 10. What is the difference between inter-thread communication and inter-process communication, and how is it implemented during the Android development process 11. Briefly describe several details of memory optimization in the project My personal understanding is that Android view rendering must go through three steps: measure, layout, and draw. The measure process is continuously traversed in a tree structure. If the UI level is deeply nested, It will definitely take a lot of time, so you should try to reduce the level of nesting, ensure that the tree structure is flat, and remove views that do not need to be rendered Custom view steps: General steps for Android custom View Volley tutorial blog.csdn.net/jdfkldjlkjd… Basic difference between TCP and UDP UDP application scenarios: Single case mode: Singleton mode It is an object creation mode that is used to generate a specific instance of an object. It can ensure that only one instance of a class in the system is generated. Adapter mode: Convert an interface into another interface that the customer wants. The adapter mode enables classes with incompatible interfaces to work together. Its alias is wrapper (Wrapper) Decoration mode : Dynamically add some additional responsibilities to an object. In terms of adding object functions, the decoration mode is more flexible than generating subclass implementations. Decoration pattern is an object structural pattern. Usage scenarios: Advantages: For extending the function of an object, the decoration mode is more flexible than inheritance and will not lead to a sharp increase in the number of classes. The functionality of an object can be extended in a dynamic way. An object can be decorated multiple times by using different specific decoration classes and the permutations and combinations of these decoration classes. Practical application: Implementation of Context class in Android Appearance mode: The main purpose is to reduce the number of external and internal subsystems The interaction between modules makes it easier for the outside world to use the subsystem. It is responsible for forwarding client requests to various modules within the subsystem for processing. scenes to be used: **Composition mode:**Organize objects in a tree structure to achieve a "part-whole" hierarchy, so that the client Consistent use of single objects and combined objects. Usage scenarios: Advantages: 1. High-level module calls are simple
2. Freely add nodes ** Template method: ** is to delay the steps in the algorithm to subclasses through an algorithm skeleton, so that subclasses can override the implementation of these steps to implement a specific algorithm. . Its usage scenarios: Observer pattern: Define a one-to-many relationship between objects Dependency relationships ensure that whenever the state of an object changes, its related dependent objects are notified and automatically updated. Usage scenarios: Specific application: For example, in the callback mode, after the instance that implements the abstract class/interface implements the abstract method provided by the parent class, the method is returned to the parent class to handle notifyDataSetChanged in Listview In RxJava Observer pattern **Responsibility chain mode:**A request has multiple objects to process. These objects are a chain, but which object is processed will be determined based on conditional judgment. If it cannot Handling is passed to the next object in the chain until an object handles it. Usage scenarios:1. There are multiple objects that can handle the same request. The specific object that handles the request will be determined at runtime.
2. Submit a request to one of multiple objects without explicitly specifying the recipient. Practical application:Try...catch statement
OrderedBroadcast
MotionEvent:actionDwon actionMove actionUp
Three important methods of the event distribution mechanism: dispatchTouchEvent. onInterceptTouchEvent. onTouchEvent **Strategy pattern:**Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithm to change independently of the client using it. Usage scenarios of the strategy pattern: A class defines a variety of behaviors, and these behaviors appear in the form of multiple conditional statements in the methods of this class. Then the strategy pattern can be used to avoid using a large number of conditional statements in the class. Usage scenarios: A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the methods of this class, then you can use the strategy pattern to avoid Use lots of conditional statements. Advantages:1.Context and specific strategy ConcreateStrategy are loosely coupled.
2. The strategy mode satisfies the open-close principle Specific application: The basic unit of byte stream operation is byte; the basic unit of character stream operation is Unicode code element (2 bytes).
Byte streams do not use buffers by default; character streams use buffers. Byte stream is usually used to process binary data. In fact, it can process any type of data, but it does not support direct writing or reading of Unicode code elements; character stream usually processes text data, and it supports writing. and read Unicode code elements. Reference to understand the difference between character stream and byte stream in Java View and ViewGroup The basic drawing process Only one In this case, it is feasible to do this: a large object is declared in the try statement, causing OOM, and it can be confirmed that the OOM is caused by the object declaration in the try statement, then these objects can be released in the catch statement , solve the OOM problem and continue executing the remaining statements. But this is usually not the appropriate approach. In addition to explicitly catching OOM, there are more effective ways to manage memory in Java: such as SoftReference, WeakReference, hard disk cache, etc. Before the JVM runs out of memory, GC will be triggered multiple times, and these GCs will reduce the efficiency of program operation. If the cause of OOM is not the object in the try statement (such as a memory leak), then OOM will continue to be thrown in the catch statement Java's StrongReference, SoftReference , The difference between WeakReference and PhantomReference blog.csdn.net/u010652002/… Answer: blog.csdn.net/xmc28114194… Answer: Whenever you need to use a database, you need to use the openDatabase() method of DatabaseManager to obtain the database. This method uses the singleton mode. , ensuring the uniqueness of database objects, that is, the SQLite objects used every time the database is operated are obtained consistently. Second, we will use a reference count to determine whether to create a database object. If the reference count is 1, we need to create a database. If it is not 1, we have already created it.
In the closeDatabase() method, we also judge the value of the reference count. If the reference count drops to 0, it means we need to close the database. The general approach is that in the case of multi-threaded access, you need to encapsulate a DatabaseManager yourself to manage the reading and writing of the Sqlite database. Synchronization is required, asynchronous is required, and asynchronous is required. Do not directly operate the database, which is easy to occur. The operation after locking failed because of the lock problem. This answer refers to this article blog.csdn.net/rockcode_li... Analysis: leetcode The intersection point of two linked lists www.360doc.com/content/16/… There are the following ideas: (1) Brute force cracking, traverse all linked list A node, and for each node, it is compared with all nodes in the linked list B, and the exit condition is to find the first equal node in B. The time complexity is O(lengthA*lengthB) and the space complexity is O(1). (2) Hash table. Traverse linked list A and store the nodes in the hash table. Then traverse the linked list B, and for each node in B, search the hash table. If it is found in the hash table, it means that it is the node where the intersection begins. The time complexity is O(lengthA lengthB), and the space complexity is O(lengthA) or O(lengthB). (3) Double pointer method, pointers pa and pb point to the first nodes of linked lists A and B respectively. Traverse linked list A and record its length lengthA. Traverse linked list B and record its length lengthB. Because the lengths of the two linked lists may be different, for example, in the case given in the question, lengthA=5, lengthB=6, then the difference is lengthB- lengthA=1, and the pointer pb is changed from the first node of linked list B Start taking one step, which points to the second node, pa points to the first node of linked list A, and then they take one step at the same time. When they are equal, they are the intersection nodes. Nowadays, Android development is not as popular as in previous years, but senior talents are still in short supply. Do you look familiar with this sentence, because senior web talents are also in short supply, c senior Talents are still in short supply, so in the era of artificial intelligence, there will also be a shortage of high-level talents in the era of artificial intelligence! It seems that people who are high-level talents are also high-level talents in other fields, and it is not because they choose the popular ones that everything will go smoothly. There is a mixed bag of articles related to senior engineer interviews online, either a bunch of content, or the quality of the content is too shallow. In view of this, I have compiled the following Android development senior engineer interview questions and answers to help you. I was successfully promoted to a senior engineer. Currently, I am working as a senior Android engineer in a large manufacturer. In the current environment, I also want to contribute to Android engineers. I have sorted out these questions after carefully reviewing them and thinking they are good. Everyone I know that senior engineers will not be asked questions that can be expressed clearly in one or two sentences like those just starting out, so I help everyone understand by filtering good articles. I hope it will be helpful to everyone. 4. Talk about Proguard obfuscation technology
In Android, the responsiveness of applications is monitored by two system services: Activity Manager (Activity Manager) and Window Manager (Window Manager). When the user triggers an input event (such as keyboard input, button click, etc.), if the application does not respond to the user's input event within 5 seconds, Android will consider the application unresponsive and the ANR dialog box will pop up. The ANR exception pops up mainly to improve the user experience.
7. Briefly describe the internal mechanism of Android Activity
8. Give a brief introduction to a certain module (or System App) of the Android Framework layer
9. The mechanism and principle of Android Handler
The process of using Handler in the main threadwww .cnblogs.com/yangtao1995…
12. Briefly describe Android’s view level optimization, briefly describe custom View or custom Steps in defining ViewGroup
13. Select a commonly used third-party open source library and briefly describe its access steps
14. The difference between TCP and UPD and usage scenarios
15. Briefly describe the concept of a design pattern, and briefly talk about what design patterns are used in the framework layer
16. Byte stream The difference from character stream
17. View drawing process, whether to measure the parent View first or the child View first
18. Can the OOM exception be caught by try...catch (or can the Out Of Memory Error be captured with try-catch to avoid its occurrence?)
19. The difference between WeakReference and SoftReference
20. Please calculate the memory occupied by a 100 pixel*100 pixel picture
21.Principle of okHttp implementation
22. What interceptors does okHttp have?
23. Calculate 1 2! 3! 4! 5! ... 20! Result, implemented in code
24. Write the singleton mode, which ones are thread-safe, and why they are thread-safe
25.Retrofit implementation principle
26.What are the formats of android pictures?
27.Can sqlite perform multi-threaded operations? How to ensure the security of multi-threaded database operations Sex
28. There are two linked lists with known lengths. How to determine the intersection of the two linked lists
End
The above is the detailed content of A compilation of problems encountered by Android developers in interviews with Alibaba and other major manufacturers. For more information, please follow other related articles on the PHP Chinese website!