Home  >  Article  >  Web Front-end  >  A compilation of problems encountered by Android developers in interviews with Alibaba and other major manufacturers

A compilation of problems encountered by Android developers in interviews with Alibaba and other major manufacturers

藏色散人
藏色散人forward
2020-07-31 14:14:584051browse

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.

1. How to avoid memory leaks when customizing Handler

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…

2.OnNewIntent() calling timing

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复制代码

2. Override onNewIntent method in MainActivity

<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>复制代码

3.Main2Actvity executes click jump , MainActivity is reused, and the onNewIntent method is executed

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 ListView
  1. Function of GridView
  2. Function of horizontal ListView
  3. Function of horizontal ScrollView
  4. Waterfall flow effect
  5. Easy to add Item addition and removal animation
  6. But it’s quite depressing The problem is that the system does not provide ClickListener and LongClickListener. But we can also add it ourselves, it just requires more code. There are many ways to implement it. You can listen and judge gestures through mRecyclerView.addOnItemTouchListener.

Of course, you can also provide callbacks yourself through the adapter

Reference

jcodecraeer.com/a/anzhuokai… blog.csdn.net/lmj62356579… www.360doc.com/content/16/…

4. Talk about Proguard obfuscation technology

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.

  • Android system components, system components have fixed methods that are called by the system.
  • Referenced by Android Resource file. The name has been fixed and cannot be confused, such as a custom View.
  • Android Parcelable, need to use android serialization.

Other Anroid official recommendations are not confusing, such as

  • android.app.backup.BackupAgentHelper 
  • android.preference. Preference 
  • com.android.vending.licensing.ILicensingService 
  • Java serialization method, system serialization requires a fixed method. Enumeration, the system needs a fixed method to handle enumeration.
  • Local method, local method name cannot be modified 
  • annotations Annotations 
  • Database driver 
  • Some resource files use reflection
  • 5. ANR scenarios and solutions

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.

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

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 thread

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

www .cnblogs.com/yangtao1995…

11. Briefly describe several details of memory optimization in the project

Answer:

  1. After querying the database, close the Cursor object in time.
  2. Remember to call the unregisterReceiver() method in the Activity's onPause method to unregister the broadcast
  3. To avoid Content memory leaks, for example, do not set the Drawer object to static on versions prior to 4.0.1. When a Drawable is bound to a View, the View object will actually become a callback member variable of the Drawable. In the above example, the static sBackground holds a reference to the TextView object lable, and lable only has a reference to Activity, and Activity will Holds references to other more objects. The life cycle of sBackground is longer than Activity. When the screen is rotated, the Activity cannot be destroyed, which causes a memory leak problem.
  4. Try not to use non-static inner classes in Activity, because non-static inner classes will implicitly hold references to external class instances. When the declaration period of the reference of non-static inner classes is longer than the declaration period of Activity, This will cause the Activity to be unable to be recycled normally by GC.
  5. Use Thread with caution! ! This is a mistake that many people make: A characteristic of Threads in Java is that they are directly referenced by the GC Root. That is to say, the Dalvik virtual machine holds strong references to all activated threads, causing GC These thread objects can never be recycled unless the thread is manually stopped and set to null or the user directly kills the process. Therefore, when using threads, you must consider stopping and releasing the thread in time when the Activity exits.
  6. When using Handler, either place it in a separate class file or use a static internal class. Because static inner classes do not hold references to external classes, they will not cause memory leaks of external class instances

12. Briefly describe Android’s view level optimization, briefly describe custom View or custom Steps in defining ViewGroup

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

13. Select a commonly used third-party open source library and briefly describe its access steps

Volley tutorial blog.csdn.net/jdfkldjlkjd…

14. The difference between TCP and UPD and usage scenarios

Basic difference between TCP and UDP

  1. Connection-based and connectionless
  2. TCP requires more system resources and less UDP;
  3. UDP program structure is simpler
  4. Stream mode (TCP) and datagram mode (UDP);
  5. TCP guarantee Data correctness, UDP may lose packets
  6. TCP guarantees data order, UDP does not guarantee

UDP application scenarios:

  1. Datagram-oriented method
  2. Most network data are short messages
  3. Have a large number of Clients
  4. No special requirements for data security
  5. The network burden is very heavy, but High requirements for response speed

15. Briefly describe the concept of a design pattern, and briefly talk about what design patterns are used in the framework layer

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:

  1. Add responsibilities to a single object in a dynamic and transparent manner without affecting other objects.
  2. The decoration mode can be used when the system cannot be extended through inheritance or when inheritance is not conducive to system expansion and maintenance.

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:

  1. When you want to provide a simple interface for a complex subsystem
  2. There was a huge dependency between the client program and the implementation part of the abstract class
  3. When When you need to build a hierarchical subsystem

**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:

  1. Need to represent the entire or partial level of an object
  2. Allow the client to ignore changes in different object levels

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:

  1. Multiple subclasses have public methods, and the logic is basically the same
  2. Important and complex algorithms, The core algorithm can be designed as a template method.
  3. When refactoring, the template method pattern is a frequently used pattern

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:

  1. An abstract model has two aspects, one of which depends on the other.
  2. An object's Changes will cause one or more other objects to also change
  3. Need to create a trigger chain in the system

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:

  1. HttpStack
  2. Volley Framework

16. Byte stream The difference from character stream

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

17. View drawing process, whether to measure the parent View first or the child View first

View and ViewGroup The basic drawing process

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?)

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

19. The difference between WeakReference and SoftReference

Java's StrongReference, SoftReference , The difference between WeakReference and PhantomReference

20. Please calculate the memory occupied by a 100 pixel*100 pixel picture

blog.csdn.net/u010652002/…

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?

Answer: blog.csdn.net/xmc28114194…

27.Can sqlite perform multi-threaded operations? How to ensure the security of multi-threaded database operations Sex

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...

28. There are two linked lists with known lengths. How to determine the intersection of the two linked lists

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.

End

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.

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete