High-frequency interview questions for Android posts (to be added)

Android development post high-frequency questions

1. Scope in java

  • public: can be accessed by all other classes
  • private: can only be accessed and modified by yourself
  • protected: It can be accessed by itself, subclasses and classes in the same package
  • default: Classes in the same package can be accessed, and no modifiers are added to the declaration, which is considered friendly.

2. The difference between hashcode(), equals, and ==

  • If two objects equals are equal, the Java runtime environment will think that their hashcodes must be equal.
  • If two objects equals are not equal, their hashcodes may be equal.
  • If two objects have the same hashcode, they equals are not necessarily equal.
  • If two objects have unequal hashcodes, their equals must be unequal.
  • == If the equal sign is compared to the basic data type (int long float ...), it is the value
  • If the == equal sign compares objects, it compares whether the addresses in the objects are equal.
  • equals mainly compares whether two strings/characters are equal.

3. The difference between HashMap and HashTable

HashMap is thread-unsafe: it means that when using HashMap in multiple threads, for example, thread A (customer) and thread B (customer) go to share resources (windows) to buy tickets, and when there is 1 ticket left, the thread is not safe. , both of them will buy this ticket at the same time.

HashTable is thread-safe: it means that when using HashTable in multiple threads, buying a ticket is an example: if A buys a ticket first, then A has a ticket, and B cannot buy a ticket. It mainly depends on who has the fastest Internet speed and who buys it first. The reason for making threads safe is that the keyword synchronized is added to the method, so that threads must be executed synchronously, that is, thread B can only execute after thread A finishes executing.

4. The difference between ArrayList and LinkedList

ArrayList: The bottom layer is based on the array form. The characteristics of the array are that it occupies a continuous memory space and realizes fast random access internally. Macroscopically, the search is fast, and the insertion and deletion of data is very slow. Why does this happen? Answer: Because the array query data is fast, the memory is continuous, and the insertion and deletion are slow because if a value is inserted in the middle of the array, then all the subsequent array data will be moved back, the overhead is relatively large, and the speed is relatively fast. Slow, delete is the same.

LinkedList: The bottom layer is based on the form of linked list. The form of linked list is (a node, which contains the node data and the pointer to the next node). Macroscopically, insertion and deletion are faster, and query is slower. Why does this happen? Answer: Insertion and deletion are fast, because of the characteristics of the linked list. When deleting a data node, the linked list will be divided into two halves to determine whether the deleted node is in the first half or the second half. If it is in the first half, then From the end node of the first half, traverse from back to front to find the node to be deleted. If it is the second half, from the head of the linked list in the second half, traverse from front to back to find the node to be deleted. Instead of traversing all of them, it is enough to find the previous pointer field pointing to the deleted node. The slow query is because the linked list requires the program to find the pointer fields and traverse them one by one, which is expensive.

Special case:

ArrayList inserts a number at the back of the array, and there is no need to change the position of the array, because inserting a number at the back does not need to change the previous number. This situation is similar to that of linkedList.

LinkedList to query a number, if that number (node) is right in the middle, it is almost as fast as ArrayList query, because LinkedList is divided into the first half and the second half to query the number (node).

ArrayList expansion mechanism: When the capacity is full, an ArrayList that is 1.5 times larger than the previous one will be recreated, and then the previous ArrayList will be put into the ArrayList that is 1.5 times larger in order.

5. Internal principle of HashMap

The bottom layer of HashMap stores data in the form of array + linked list, that is, each array element is a linked list, called a bucket. HashMap stores key-value pairs for fast access to data; allows null key/value

put() operation: First, the hashcode value of the key is calculated, and the modulo operation is performed on this value and the length of the array to obtain the element (bucket) in the array, which is the storage location of put. If the key is the same, the previous value value is replaced .

get() operation: First, the hashcode value of the key is calculated, and the modulo operation is performed on this value and the length of the array to obtain the element (bucket) in the array, and then the hashcode calculation is performed on its key. If the hashcode value is the same (collision occurs ), then compare whether their equals are the same, and if they are the same, find the position to be obtained and take it out. If there is no collision, no equals is needed.

HashMap expansion mechanism: threshold = loadfactor*current capacity, load factor defaults to 0.75. The internal parameters of HashMap are loadfactor and current capacity. The first parameter defaults to 0.75, (75%), and the second parameter is the size of HashMap. If the capacity of HashMap is occupied by 75%, it will re-expand from twice the capacity.

6. Activity life cycle in Android

onCreate()

Executed when the activity is created

onStart()

Executed when the activity is visible, that is, when it enters the foreground

onResme()

This method is executed when the activity is ready to interact with the user, and the activity at this time must be at the top of the return stack and in the running state.

onPause()

Execute when the active part is visible, statement: the dialog prompt window will not execute this method, those on the Internet are stunned, reposted without testing. Why do you say that it is executed when the activity part is visible? It will only be called when the activity is set to the dialog form.

Add android:theme="@android:style/Theme.Dialog" . Modify Activity to Dialog style. can

Also called when the current activity is all invisible.

onStop()

Called when the activity is not visible

onDestory()

Called when the activity is destroyed, such as pressing the back button of the mobile phone, or setting Finish()

Supplement the life cycle of Intent [A jumps to B]

A: represents the life cycle of A;

B: represents the life cycle of B;

onCreate(A)→onStart(A)→onResme(A)→onPause(A)→onCreate(B)→onStart(B)→onResme(B)→onStop(A)

when returning to A

onPause(B)→onRestart(A)→onStart(A)→onResme(A)→onStop(B)→onDestroy(B)

Dialog and AlertDialog will not affect the life cycle of Activity

Because the dialog is attached to the activity, it is not blocked.

7. Problems when Intent transfers data and Bundle transfers data

The data type passed by Intent must be the eight basic data types (int, float...) and the class that must implement serialization.

Serialization (Servalable, Parceable) two kinds of serialization.

What is serialization: Our objects are not only stored in memory, but also need to be transmitted over the network, or saved and loaded next time, so Java serialization technology is required. Java serialization technology converts objects into an array of binary bytes. By saving the binary data to disk or transmission network, disk or network receivers can deserialize the class on the template of the object’s category. Object, to achieve the purpose of object persistence.

The difference between the two serializations: the first one is the serialization that comes with java, which is used to save the data serialization from the file to the disk, but it will generate a large number of temporary variables, resulting in a very stuck (GC (garbage collection) occurs Frequent), not suitable for transferring data in memory.

The second is Android's built-in serialization, which cannot serialize data to disk, and serializes data transmission in memory from binary form.

8. Four major components in Android

  • Activity
  • Broadcast (BoderCast Recevier)
    is divided into ordered broadcast and disorderly broadcast, and also divided into sticky broadcast and standard broadcast, static registration broadcast and dynamic broadcast. The difference between ordered and unordered is that the priority of the broadcast is set. The higher the priority, the broadcast will be executed first; the difference between sticky and standard is: sticky broadcast does not consider whether other apps have registered when sending broadcasts to me. Once I If you register for the broadcast, you will receive it, and if you are not registered, you will wait to receive it. Standard broadcasts will not be like this. Static broadcast needs to be registered in AndroidManifest.xml, and the broadcast is still running when the program is not started. In the case of dynamic broadcasting, there is no need to register in AndroidManifest.xml, it is registered in the form of code, and the broadcast will only start when the program starts.
  • Service (Service)
    background service for the interaction between the client and the server. There are two ways to start
    1. onBindService
    life cycle: onCreate, onStart, onBind, onStop, onDestory. After onCreate is created, it will no longer be executed. When the broadcast is executed again, it will only continue from onStart. onBind returns a bind object to the client.
    2. onStartService
    life cycle: onCreate, onStart, onStartCommnd, onStop, onDestory. As above, onCreate will not execute after creation.
    3. IntentService
    is a subclass of service. Thread tasks are started by calling onHandleIntent. Each task is executed synchronously by threads, that is, after one thread executes, another thread is executed. Come one by one. When will this subcategory be used, for example (a large task can be divided into many subtasks, such as an app store, when downloading many apps, you can consider this, but the apps downloaded in the app store are generally downloaded asynchronously, not will be queued for download)
  • The content provider (content provider)
    accesses data across applications, directly manipulates the sqlite database, and so on. For example, directly access the contacts in the mobile phone.

9. Five major layouts in Android

  1. FrameLayout (frame layout, frame layout)
    all controls will be displayed in the upper left corner of the screen in turn, will overlap. FrameLayout is the simplest layout object. It's customized as a blank spare area on your screen that you can later fill with a single object—for example, a picture you want to post. All child elements will be fixed to the upper left corner of the screen; you cannot specify a position for a child element in a FrameLayout. The latter child element will be overlaid and filled directly on top of the previous child element, partially or completely blocking them (unless the latter child element is transparent). This layout can be regarded as a pile of things at the foot of the wall. There is a square rectangle at the upper left corner of the wall. We put the first thing, and if we want to put another one, we put it on top of the original place, and put it one by one. will cover the original. This layout is relatively simple, and only a few relatively simple things can be placed.
  2. LinearLayout (linear layout)
    Linear layout is one of the most commonly used classes in all layouts, and it is also the parent class of RadioGroup, TabWidget, TableLayout, TableRow, ZoomControls classes. LinearLayout can make its child elements line up vertically (android:orientation="vertical") or horizontally (android:rientation="horizontal") (the default is to arrange vertically when the direction is not set). When the layout is vertical, there is only one element in each row, and multiple elements are arranged vertically downwards; when the layout is horizontal, there is only one row, and each element is arranged to the right in turn.
    There is an important attribute android:layout_weight=”1” in linearLayout. This weight represents the line spacing when it is vertically laid out; it represents the column width when it is horizontal; the larger the weight value, the larger it will be.
  3. AbsoluteLayout (absolute layout)
    Since AbsoluteLayout is no longer supported, we will not introduce it here. In actual development, it is also strongly recommended not to use the AbsoluteLayout layout method, because different mobile phones have different resolutions, and there are fixed pixels for placing components. At the same time, each layout also has its limitations, so in actual development, we often nest one or more layout methods at the same time to present a more beautiful user interface.
  4. RelativeLayout (relative layout)
    RelativeLayout allows child elements to specify their position relative to other elements or parent elements (specified by ID). Thus, you can align two elements right-aligned, top-bottom, or centered on the screen. Elements are arranged in order, so if the first element is in the center of the screen, then other elements relative to this element will be arranged in the relative position of the center of the screen. If using XML to specify the layout, the associated element must be defined before you can define it.
  5. TableLayout (table layout)
    table layout, assigns the position of child elements to rows or columns. A TableLayout consists of many TableRow (lines). TableLayout container will not display row, cloumns or cell border lines. Each row has 0 or more cells; each cell has a View object. A table consists of columns and rows made up of many cells. Tables allow cells to be empty. Cells cannot span columns, unlike in HTML.

10. What kinds of animations are there in Android?

1. Motion tweening/view animation

The actual width and height of the view are not changed, but the display position of the view is changed. Then during the animation movement, the click event is invalid. Because the actual view didn't move

2. Frame animation

For a frame-by-frame animation, remember that the picture should not be too large, which will easily lead to OOM and memory overflow.

3. Property animation

The actual position of the view is changed, and the click event can be realized.

some properties of animation

    名称       	    原理     	对应的Animation的子类    

Translation animation (Translate) Move the position of the view TranslateAnimation class
Scale animation (Scale) Zoom in/out the size of the view ScaleAnimation class
Rotation animation (Rotate) Rotate the angle of the view RotateAnimation class
Transparency animation (Alpha) Change the transparency of the view AlphaAnimation class

11. Four startup modes in Android

1.standard (default mode)

In standard mode, new activity instances will be created continuously and put into the same stack

2.singleTop

If the current instance is at the top of the stack of the current task, it will be reused directly. If the current instance is no longer at the top of the stack, a new instance will be created.

3.singleTask

The page with singleTask is set, as long as there is this instance in the task, it will be reused all the time, and every time the existing instance is reused, the other instances above will be cleared, and it will be directly promoted to the top of the stack to display itself

4.singleInstance

For pages with singleInstance set, a new task stack is created for this page at the beginning, and then the pages in this stack are reused all the time. Note that only this mode creates a new stack for the initialized page. The rule of the final return is that first all the stacks where this page is located are exhausted, and then each page of the next stack is popped up.

12. Handler cross-thread mechanism

Let's talk about it roughly.

Divided into 4 roles:

handler: Cross-thread data receiver.

message: The message body of the message transmitted across threads.

message enqueue: message queue, which stores messages in the form of a linked list. Messages are divided into delayed messages and non-delayed messages. The greater the delay, the further back the message queue will be placed.

Loopr: The manager of the message queue (message enqueue), which controls the storage and release of messages in the message queue. The thread establishes its own message loop through the Looper, and the Looper is responsible for taking out the message from the MessageQueue and distributing it to the specified target Handler object of the message.

general process

When the sub-thread sends data to the main thread, call in the sub-thread, handler.sendMessage(message) (the default delay is 0ms) When sending a message, it will be called step by step

In handler.sendMessageDelayd(message), it implements the current time + message delay time, then calls handler.sendMessageAttime(message) to determine the delayed sending time of the message, and then calls message enqueue to prepare to add the message to the message queue. At this time The management right is handed over to the looper, and the current thread will be obtained. Set the current thread as a safe thread (ThreadLocal) because messages can be sent to the main thread in many sub-threads. Each thread must be isolated to prevent data confusion, and then add the message In the message queue, the target.dispatchMessage() method is called, the target is the handler, and the message is distributed to the handler, that is, the message is called back to the handler, and a handler cross-thread operation is completed.

13. MVP mode

M (model): almost where the logic is processed

V (view): Actvivity is responsible for putting in and taking out data from M for display

P (presenter): middleman. M and V cannot interact directly, but through P. V→P↔M, V gives the data to P, P to M, after processing the data, M to P, and P to V.

The advantage of this design: low coupling and high cohesion, no need to change one place but everywhere.

14. What is ANR

Application is not responding.

  1. If the main thread does not finish processing the input event within 5 seconds,
    the premise of generating this kind of ANR is that there must be an input event. If the user does not trigger any input event, even if the main thread is blocked, ANR will not be generated, because the InputDispatcher does not distribute events. For the application, of course, it will not detect the processing timeout and report ANR. That is, the process of the user operating the APP == input event.
  2. The main thread does not finish executing the onReceive function of BroadcastReceiver within 10 seconds, and the background process takes 60 seconds.
    In this case, the ANR system will not display the dialog box prompt, but only output the log.
  3. The main thread does not complete the execution of each lifecycle function of Service within 20 seconds, and the background process takes 200 seconds.
    Similarly, the ANR system in this case will not display a dialog box prompt, but only output the log.

15. What is memory leak and out of memory (OOM)

1. Memory overflow

The system can no longer allocate the space you need. For example, the system now only has 1G space, but you want 2G space, which is called memory overflow. For example, if you load a lot of large pictures every time, and then don’t release the picture resources, over time, the picture will stay in the memory, and it will crash when the memory is exhausted.

Therefore, the picture should be released and cleared in time. Bitmap is a format for storing pictures. bitmap.recycler() to release.

2. Memory leaks

The object pointed to by the strong reference will not be recycled, which may lead to memory leaks. The java (jvm) virtual machine would rather throw OOM than recycle the object it points to. This means that when you use resources, you open up a space for him. You forgot to release the resource when you used it up. At this time, the memory is still occupied. It doesn’t matter once, but if there are too many memory leaks, it will lead to memory overflow. One of the functions of jvm is to clear garbage, such as some unavailable instances, new objects, etc., to make memory more friendly, which is also a unique mechanism of java.

Handlers can also cause memory leaks. Because the handler has to deal with the thread, if the thread is not processed and the activity is actively finished, then the handler will always deal with the thread. Solution: Change the handler to a static inner class static myHandler class extend handler{} because a static inner class will not hold a reference to an outer class. is a separate "class".

You can also use weak references and soft references to solve this problem.

16. What are soft references, weak references, and strong references

Java's memory allocation and memory recovery do not require programmers to be responsible, and are all in charge of the great JVM. Whether an object can be recycled depends mainly on whether there are references pointing to this object. The professional point is called reachability analysis. .

There are two main purposes for Java to design these four references:

  • It allows programmers to determine the life cycle of an object through code;
  • Good for garbage collection.

I won't talk about the knowledge of JVM.

1. Strong reference

Strong references are the most common kind of references. 99.9999% of the code we write are strong references:

Object

new

Object

This is a strong reference, whether it can be seen everywhere in the code, the most cordial.

2. Soft references

SoftReference<Student>studentSoftReference=new SoftReference<Student>(new Student());
//软引用就是把对象用SoftReference包裹一下,当我们需要从软引用对象获得包裹的对象,只要get一下就可以了:
Student student = studentSoftReference.get();      
System.out.println(student);

When the memory is insufficient, the GC (garbage collection) of the JVM will be triggered. If the memory is still insufficient after the GC (garbage collection), the object wrapped by the soft reference will be killed, that is, only when the memory is insufficient, the JVM will recycle the object. object.

What is Garbage Collection:

The garbage collected by garbage collection is useless classes, useless objects, etc. Useless classes and instances are cleaned up to save memory when the program is running.

3. Weak citations

Similar to the code above. Wrapped with a WeakReference object

The characteristic of weak references is that regardless of whether the memory is sufficient, as long as GC occurs, it will be recycled:

Guess you like

Origin blog.csdn.net/q1210249579/article/details/111387329