The latest intermediate Android interview questions in July 2021

Table of contents

1. Detailed Activity life cycle

2. Explain the characteristics of common Android layouts

3. Please explain the inheritance relationship and function of the Context class

4. Four LaunchMode of Activity

5. View drawing process

6. The way of data communication between Android multi-threads

7. The principle of Handler

8. How to transfer data between two Activities?

9. Brief description of TCP, UDP, Socket

10. What are the five data storage methods in Android?

11. The difference between process and thread

12. Briefly introduce the usage of keywords final and static

13. The difference between an array and a linked list.

14. The difference between ArrayList and LinkedList, and the application scenarios.

15. What is the use of a.hashcode(), and what is the relationship with a.equals(b)

16. In jdk1.5, generics are introduced, what problems does the existence of generics solve?

17.Android performance optimization

18. The difference between Thread and Runnable

19. The difference between interface and abstract class

20. The difference between Set, List and Map in Java


1. Detailed Activity life cycle

onCreate : This method is called back when the Activity is created. It is the first method called in the life cycle. We generally need to rewrite this method when creating an Activity, and then do some initialization operations in this method, such as through setContentView Set the resources of the interface layout, initialize the required component information, etc. 

onStart : When this method is called back, it means that the Activity is starting. At this time, the Activity is already visible, but it is not displayed in the foreground, so it cannot interact with the user. It can be simply understood that the Activity has been displayed and we cannot see it. 

onResume : When this method is called back, it means that the Activity is already visible in the foreground and can interact with the user (in the Active/Running state mentioned above). The same point between the onResume method and onStart is that both indicate that the Activity is visible, but When onStart is called back, the Activity is still in the background and cannot interact with the user, but onResume has been displayed in the foreground and can interact with the user. Of course, from the flowchart, we can also see that when the Activity stops (the onPause method and the onStop method are called), the onResume method will also be called when it returns to the foreground, so we can also initialize some resources in the onResume method, such as reinitialization Resources released in the onPause or onStop method. 

onPause : When this method is called back, it means that the Activity is stopping (Paused form). Generally, the onStop method will be called back immediately. But through the flow chart, we can also see that the onResume method is directly executed after the onPause method is executed. This is a relatively extreme phenomenon. This may be due to user operations that make the current Activity retreat to the background and then quickly return to the For the current Activity, the onResume method will be called back. Of course, in the onPause method, we can do some data storage or animation stop or resource recovery operations, but it should not be too time-consuming, because this may affect the display of the new Activity - after the onPause method is executed, the onResume of the new Activity method will be executed. 

onStop : Generally, it is executed directly after the onPause method is executed, indicating that the Activity is about to stop or is completely covered (Stopped form). At this time, the Activity is invisible and only runs in the background. Similarly, some resource release operations can be done in the onStop method (not too time-consuming). 

onRestart : Indicates that the Activity is being restarted. When the Activity changes from invisible to visible, this method is called back. In this case, when the user opens a new Activity, the current Activity will be suspended (onPause and onStop are executed), and then when returning to the current Activity page, the onRestart method will be called back. 

onDestroy : At this time, the Activity is being destroyed, and it is also the last method executed in the life cycle. Generally, we can do some recycling work and final resource release in this method. 

2. Explain the characteristics of the common layout of A ndroid

FrameLayout frame layout, display features: all sub-controls are displayed in the upper left corner of FrameLayout by default, and they will overlap and display together.

LinearLayout linear layout, display features: all sub-controls are arranged horizontally or vertically.

RelativeLayout relative layout, display features: similar to LinearLayout layout, all sub-controls are displayed in the upper left corner of RelativeLayout by default.

GridLayout grid layout, display features: all sub-controls are arranged horizontally and sequentially in GridLayout by default. When only waiting for the number of columns in each row, when the specified number of columns is reached, the display will automatically wrap.

TableLayout table layout, table layout is similar to grid layout, but it should be noted that table layout cannot span rows, only columns.

3. Please explain the inheritance relationship and function of the Context  class

Context is the interface of global information in the application environment, which is mostly translated into context. It integrates many system-level services, which can be used to obtain classes and resources in the application, and can perform application-level invocation operations, such as starting Activity, Service, etc., and the Context class is abstract and does not contain specific function implementations.

Both Application and Activity indirectly inherit Context

The difference between getApplication and getApplicationContext

The result returned by getApplication is Application, and the Applications returned by different Activities and Services are all the same global object

getApplicationContext also returns the Application object, but the return type is Context, see its implementation

The difference between getContext and getActivity

this: Indicates the current object; generally speaking, in which class it is called, it points to the object.

getContext(): This is a method provided in the View class. It can only be called in a class that inherits View. It returns the Activity Context in which the current View is running.

getActivity(): Get the Activity object to which the Fragment is attached. The reason why getActivity() in Fragment is not recommended is as follows: This method will return the Activity attached to the current Fragment. When the Fragment life cycle ends and is destroyed, getActivity() returns null, so pay attention to judging null or capturing when using it Null pointer exception.

4. Four LaunchMode of Activity

Standard: The standard startup mode, if an activity needs to be started, an instance of the activity will be created. It is also the default startup mode of the activity.

SingeTop: If the started activity is already at the top of the stack, then a new activity instance will not be recreated. Instead, the activity instance object at the top of the stack is reused. If it is not at the top of the stack, the instance object of the activity will still be recreated.

SingleTask: When the activity with the singleTask startup mode is set to start, if it is located in the activity stack, the activity will be reused. In this way, all the activities above the instance will be popped out of the stack in turn, that is, the corresponding onDestroy( ) method until the current activity to be started is at the top of the stack. Generally used in the atlas of web pages, one-click to exit the current application.

singleInstance: If the activity using the singleInstance startup mode will reuse the existing activity instance when it starts. No matter which application the instance of this activity is located in, it will share the instance object of the started activity. The activity that uses the singlestance startup mode will open a shared stack separately, and only the current activity instance object exists in this stack.

5. View drawing process

The main process in View drawing is divided into three stages: measure, layout, and draw.

measure: Calculate the size according to the MeasureSpec passed by the parent view.

layout: According to the layout size and layout parameters obtained by the measure sub-View, place the sub-View in an appropriate position.

draw : Draw the View object to the screen

6. The way of data communication between Android multi-threads

1、handler
2、Activity.runOnUIThread(Runnable)
3、View.Post(Runnable)
4、View.PostDelayed(Runnabe,long)
5、AsyncTask

7. The principle of Handler

Handler four components

                 1)Message

                       Message is a message passed between threads, and it can carry a small amount of information internally for exchanging data between different threads.

                       Example: The what field, arg1 field, and arg2 field of Message carry integer data, and the obj field carries an Object object.

                 2)Handler

                       Processor, which is mainly used to send and process messages. Sending a message generally uses the sendMessage() method of the Handler. After the message is processed, it is finally passed to the handlerMessage() method of the Handler.

                 3)MessageQueue

                      Message queue, which is mainly used to store all messages sent through Handler, these messages will always exist in the message queue, waiting to be processed.

                      Note: There will only be one MessageQueue object per thread.

                 4)Looper

                     It is the steward of MessageQueue in each thread. After calling Looper's loop() method, it will enter an infinite loop. Whenever a message is found in MessageQueue, it will be taken out and passed to Handler's handleMessage() method. .

                     Note: There will only be one Looper object per thread.

8. How to transfer data between two Activities?

Intent can start an Activity, and can also pass data when starting the Activity. The putExtra() method is provided in the intent, which can temporarily store the data we want to pass in the intent. After starting another Activity, pass getIntent().getStringExtra() (where getStringExtra() is determined by the data type passed by the activity. is String or other types), and then taken out from the Intent.

9. Brief description of TCP, UDP, Socket

TCP/IP is the transmission control/network protocol, which is a connection-oriented protocol. Before sending data, a connection must be established (a connection must be established between the pair of the sender and the receiver). TCP provides reliable services, that is, Say, data transferred over a TCP connection is not lost, is not duplicated, and arrives in order

UDP is one of the TCP/IP protocol family. It is a connectionless protocol that does not need to establish a connection before sending data, and is an unreliable protocol. Because there is no need to establish a connection, it can be transmitted on any possible path on the network, so whether it can reach the destination, the time to reach the destination, and the correctness of the content cannot be guaranteed.

A socket connection is a so-called long connection, and the client and server need to be connected to each other . Two programs on the network exchange data through a two-way communication connection, and one end of the two-way link is called a Socket. Socket is usually used to realize the connection between the client side and the server side. Socket is a very popular programming interface of the TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.

10. What are the five data storage methods in Android?

(1) SharedPreference, which stores less five types of data, can only be used in the same package

            Use, the generated XML format is stored in the device

(2) SQLite database, which stores various data, is a lightweight embedded database

(3) File file, generate file storage data by reading and writing

(4) ContentProvider, mainly used to allow other applications to use saved data

(5) Obtain data through the network and write data to network storage space

11. The difference between process and thread

1. A process is the smallest unit of resource allocation, and a thread is the smallest unit of program execution;

2. The process has its own independent address space. Every time a process is started, the system will allocate an address space for it, and create a data table to maintain the code segment, stack segment and data segment. Threads do not have independent address spaces, and they use the same address space share data;

3. CPU switching a thread costs less than switching processes;

4. Creating a thread has less overhead than a process;

5. Threads occupy much less resources than processes.

6. Communication between threads is more convenient. Under the same process, threads share data such as global variables and static variables, and communication between processes needs to be carried out in the form of communication (IPC); (but multi-threaded programs handle synchronization and mutual exclusion well. is difficult)

7. Multi-process programs are safer and have stronger vitality. The death of one process will not affect the other process (due to the independent address space). Multi-threaded programs are more difficult to maintain. If one thread dies, the entire process will die dropped (because of shared address space);

8. Processes have high requirements for resource protection, high overhead, and relatively low efficiency. Thread resource protection requirements are not high, but low overhead, high efficiency, and frequent switching;

12. Briefly introduce the usage of keywords final and static

final has the "final" meaning of "this cannot be changed", preventing polymorphism and inheritance.

The specific uses are:

The final class cannot be inherited, there is no subclass, and the methods in the final class are final by default.

final methods cannot be overridden by subclass methods, but can be inherited.

The final member variable represents a constant, which can only be assigned once, and the value will not change after assignment.

final cannot be used to decorate constructors.

static means "global" or "static", used to modify member variables and member methods, and can also form static static code

code blocks, but  there is no concept of global variables in the Java language.

The member variables and member methods modified by  static are independent of any object of this class, and the static object can be created after any object of it

Before accessing, there is no need to refer to any object.

It can also be modified with public or private in front of static, where private is limited access rights, and static means not to instantiate

Just use it.

Mainly used for static variables, static methods, static code blocks

Static variables: For static variables there is only one copy in memory (saving memory), JVM only allocates memory for statics once, after adding

In the process of class loading, the memory allocation of static variables is completed, which can be directly accessed by the class name (convenient), of course, it can also be accessed by the object (but

Yes this is not recommended).

Static method:  Static methods can be called directly through the class name, and any instance can also be called, so this cannot be used in static methods

and  the super keyword, cannot directly access the instance variables and instance methods of the class to which they belong (that is, member variables and member components without static

member methods ), and can only access the static member variables and member methods of the class to which it belongs. Because instance members are associated with specific objects!

Static code block: atic code block is also called static code block, which is a static statement block independent of class members in a class, and there can be multiple,

The position can be placed anywhere, it is not in any method body, these static code blocks will be executed when the JVM loads the class, if the static code block

There are multiple code blocks, and the JVM will execute them sequentially in the order in which they appear in the class, and each code block will only be executed once

Use static and final together:

static final is used to modify member variables and member methods, which can be simply understood as "global constants"!

For variables, it means that once a value is given, it cannot be modified and can be accessed through the class name.

For a method, it means that it cannot be overridden and can be directly accessed through the class name.

Pay special attention to one problem:

For  instance constants modified by static and final, the instance itself cannot be changed, but for some container types (eg,

The instance variables of ArrayList and HashMap cannot change the container variable itself, but can modify the objects stored in the container.

One point is used a lot in programming.

13. The difference between an array and a linked list.

Array: It stores elements continuously in memory; its advantage: because the data is stored continuously and the memory address is continuous, it is more efficient when searching for data; its disadvantage: before storing, we need to apply for a continuous The memory space, and the size of its space must be determined at compile time. The size of the space cannot be changed according to your needs during operation. When the data is relatively large, it may be out of bounds. When the data is relatively small, it may be wasted. memory space. When changing the number of data, the efficiency of adding, inserting, and deleting data is relatively low.

Linked list: It is a dynamic application for memory space. It does not need to apply for the size of the memory in advance like an array. The linked list only needs to be applied when it is in use. Dynamically apply or delete memory space according to needs. For data addition and deletion and insertion than arrays flexible. In addition, the data in the linked list can be in any position in the memory, and the data can be associated through the application (that is, through the pointer of the existing element).

14. The difference between ArrayList and LinkedList, and the application scenarios.

ArrayList is implemented based on arrays, and ArrayList is not thread-safe.

LinkedList is implemented based on double linked list:

scenes to be used:

( 1) If the application performs a large number of access or deletion operations on the elements at each index position, the ArrayList object is far superior to the LinkedList object;

( 2) If the application mainly loops the list, and inserts or deletes during the loop, the LinkedList object is much better than the ArrayList object;

15. What is the use of a.hashcode(), and what is the relationship with a.equals(b)

hashCode is also a method of the Object class. Returns a discrete integer of type int. Used in collection operations to improve query speed. (HashMap, HashSet, etc. compare whether they are the same)

If two objects are equals, the Java runtime environment will think that their hashcodes must be equal.

If two objects are not equals, their hashcodes may be equal.

If two objects have the same hashcode, they are not necessarily equals.

If two objects have unequal hashcodes, they must not equals.

16. In jdk1.5, generics are introduced, what problems does the existence of generics solve?

Generics are easy to use

The main goal of type-safe generics is to achieve type safety in java. Generics allow the compiler to know what the qualified type of an object is, so that the compiler can verify the type to a high degree

Elimination of mandatory type conversion makes the code more readable and reduces a lot of opportunities for errors

The advantage of introducing generics in the Java language is that it is safe and simple. The advantage of generics is that type safety is checked at compile time, and all casts are automatic and implicit, which improves code reuse.

17.Android performance optimization

1. Layout optimization

Reduce the level of nesting (constraint layout can be used), reducing the level of nesting can speed up the loading efficiency,

Use style to extract common properties of the same view, reducing duplicate code

Use include tag
2. Image optimization

The use of pictures in android is very memory-intensive.

①: When the picture is not in use, recycle () in time

②: Use L3 cache, memory-sd card-network

It is the fastest to get again in the internal memory. Due to the limited memory, it may be recycled by gc, and the pictures in the SD card will not be recycled. When the required pictures do not exist in the previous two, they will be downloaded from the Internet.

③: Compress the large image and put it in the memory, using the BitmapFactory class
3. Mass data optimization

paging load

caching method

List Item Optimization

Optimization of listview

Reuse of convertview (reuse of View)

The use of the viewholder class reduces the number of times to find controls (findviewbyid() times), and binds the holder to the view to achieve (.setTag(), .getTag())

Data pagination loading

Optimization of RecycleView

18. The difference between Thread and Runnable

1) If a class inherits Thread, it is not suitable for resource sharing. But if the Runable interface is implemented, it is easy to realize resource sharing.
2) Runnable is an interface. Thread is a class and implements the Runnable interface.
3) Implementing the Runnable interface has the following advantages over inheriting the Thread class: avoiding the limitations of inheritance, and a class can implement multiple interfaces.

19. The difference between interface and abstract class

Abstract classes and interfaces give different grammatical definitions (including method bodies, member variable modifiers, and method modifiers)

Abstraction is an abstraction of a class, and an interface is an abstraction of behavior

Abstraction embodies the inheritance relationship, which is an "is-a" relationship, while the interface only implements the contract defined by the interface, which is a "like-a" relationship

Abstraction is abstracted from the bottom up, and the interface is designed from the top down

20. The difference between Set, List and Map in Java

Set is the simplest kind of collection. The objects in the collection are not ordered in any particular way, and there are no duplicate objects. The Set interface mainly implements two implementation classes: HashSet: The HashSet class accesses the objects in the collection according to the hash algorithm, and the access speed is relatively fast

TreeSet: The TreeSet class implements the SortedSet interface, which can sort the objects in the collection.

The characteristic of List is that its elements are stored in a linear manner, and repeated objects can be stored in the collection.

ArrayList() : Represents an array whose length can be changed. Random access to elements is possible, and the speed of inserting and deleting elements into ArrayList() is slow.

LinkedList(): The linked list data structure is used in the implementation. Insertion and deletion are fast, access is slow.

Map is a collection of key objects and value objects, each of which contains a pair of key objects and value objects. Map does not inherit from the Collection interface. When retrieving elements from the Map collection, as long as the key object is given, the corresponding value object will be returned.

HashMap: Map based on the realization of the hash table. The overhead of inserting and querying "key-value pairs" is fixed. The capacity and load factor can be set through the constructor to adjust the performance of the container.

LinkedHashMap: Similar to HashMap, but when iterating through it, the order of obtaining "key-value pairs" is its insertion order, or the least recently used (LRU) order. Only slightly slower than HashMap. It is faster for iterative access because it uses a linked list to maintain internal order.

TreeMap: Implementation based on red-black tree data structure. When viewing "keys" or "key-value pairs", they are sorted (the order is determined by Comparabel or Comparator). The characteristic of TreeMap is that the results you get are sorted. TreeMap is the only Map with a subMap() method that returns a subtree.

WeakHashMao: weak key (weak key) Map, objects used in the Map are also allowed to be released: this is designed to solve special problems. If there is no reference outside the map to a certain "key", this "key" can be reclaimed by the garbage collector.

Guess you like

Origin blog.csdn.net/qq_17798399/article/details/118485843