In this paper, the author
Author: gexinzhao
Links:
http://www.jianshu.com/p/251b1bf72cd8
This article is published with permission from the author.
Well, there are 20605 words in this article. I don’t know when you will be able to finish it. I suggest you save it directly and play with smiling face
1
In September, I was anxious to change my job, and then I applied for a certain Android position. I thought that a non-211, 985 slag with no working experience like me could only be passed directly, but I was surprised to receive a phone call. After the telephone interview and three technical aspects, I finally got the OFFER after waiting for the notice, just like a dream. I was really excited.
2
When I received the notice of the HR interview, I was still very confused, because I felt that I suddenly knew nothing, so I quickly calmed down and went to the Internet to find the interview questions of a certain degree, but found that there were only questions and no answers to the questions. I had to rely on myself, just like doing the exam paper, and summarized over and over again.
In fact, most of them are used in peacetime development, but we have not summarized, when asked to answer the inevitable will be a little short, can not answer very comprehensive. The following is my personal total (BAI) knot (du), I hope to help you, but after all, the ability is limited, there are wrong places to write, but also hope light spray. I wouldn’t change it if I was.
Because the length of this article is longer recommended collection, in use to find out a look. A few knowledge points may not involve, later will try to make up. Because the interview is just to test your understanding and summary of the technology, so the summary of each point in this article is relatively simple, just let you say the general, some parts need to be able to draw schematic diagram and explain, this should be accumulated in the work.
3
Person = new Person(); Take as an example.
1). Because new uses person. class, the person. class file will be found and loaded into memory;
2). Execute the static code block in this class and initialize the Person.class class, if any;
3). Allocate memory address in heap memory;
4). Create specific attributes of objects in heap memory and initialize them by default;
5). Display initialization of attributes;
6). Initialize the constructor code block of the object;
7). Initialize the corresponding constructor of the object;
8). Pay the memory address to the p variable in stack memory
Ii. JVM knowledge, GC mechanism.
Basic Components of JVM
As you can see from the figure above, the JVM consists of four main parts:
1. ClassLoader: Loads the required classes into the JVM when the JVM starts or when the class is running. The following figure shows the entire process from Java source files to the JVM.
2. Execution engine: responsible for executing the bytecode instructions contained in the class file;
3. Memory area (also known as runtime data area) : This is the area of memory allocated for operations while the JVM is running. The runtime memory area can be divided into five areas, as shown in the figure below:
Method Area: Used to store class structure information, including constant pool, static variables, constructors, and so on. Although the JVM specification describes the method area as a logical part of the heap, it has the name non-heap, so don’t confuse it. The method area also contains a pool of runtime constants.
Java Heap: A place where Java instances or objects are stored. This is the main area of GC. It is easy to know from the stored contents that the method area and heap are shared by all Java threads.
Java Stack: The Java Stack is always associated with threads, and each time a thread is created, the JVM creates a Java Stack for that thread. This Java stack contains multiple stack frames, one created for each method run, to store local variables, operation stacks, method return values, and so on. The process of each method from invocation to completion corresponds to the process of a stack frame being pushed into and out of the Java stack. So the Java stack is off-the-shelf and private.
Program counter (PC Register) : Used to hold the memory address of the current thread execution. Because JVM programs are executed by multiple threads (threads switching in turn), to ensure that threads can switch back to their original state, they need a separate counter to record previous interruptions, visible program counters are also thread private.
Native Method Stack: Works much like a Java Stack, but serves Native methods used by the JVM.
4. Local method interface: mainly calls C or C++ implemented local methods and returns results.
The GC mechanism
Garbage collectors generally have to do two things: detect garbage; Recycle. How do you detect garbage? There are generally the following methods:
Reference counting method:
To add a reference counter to an object, incrementing the counter by one each time it is referenced; If the reference fails, minus 1. Well, here’s the problem. If I have two objects, A and B, that refer to each other, and nothing else refers to them, they’re essentially inaccessible, they’re what we call junk objects. However, there is another method:
Accessibility analysis algorithm:
The root set object is used as the starting point for the search. If any object is unreachable, it is a junk object. The root set typically includes objects referenced in the Java stack, objects referenced in the pool of methods, objects referenced in local methods, and so on.
In general, when the JVM does garbage collection, it checks whether all objects in the heap are referenced by these root set objects, and objects that cannot be referenced are collected by the garbage collector. There are also several general recycling algorithms as follows:
1). Mark-sweep
2. Copying
3). Mark-compact
4). Generation collection algorithm
Specific explanation can refer to this article also don’t point me?
http://blog.csdn.net/tonytfjing/article/details/44278233
Class loader, parent mechanism, Android class loader.
Class loader
As we all know, when we write a Java program, it is not CS or BS application, is composed of several. Class files organized into a complete Java application, when the program is running, that is, it will call an entry function of the program to call the related functions of the system. These functions are encapsulated in different class files, so it is often necessary to call methods from one class file to another. If the other class file does not exist, a system exception will be raised.
When the program is started, it does not load all the class files used by the program at one time. Instead, it dynamically loads a class file into the memory through the Java ClassLoader according to the needs of the program. Only the class file is loaded into the memory. Can be referenced by other classes. So the ClassLoader is used to dynamically load class files into memory.
Parents mechanism
1. Principle introduction
Each ClassLoader instance has a reference to a parent ClassLoader (not an inherited relationship, but a contained relationship). The Bootstrap ClassLoader does not have a parent ClassLoader itself. But can be used as a parent ClassLoader for other ClassLoader instances.
When a ClassLoader instance needs to load a class, it will try to search for the class itself and delegate this task to its parent ClassLoader. The process is checked from top to bottom. Bootstrap ClassLoader, the top ClassLoader, tries to load the class. Then the task will be handed over to the Extension ClassLoader for loading. If it is not loaded, it will be handed over to the App ClassLoader for loading. If it is not loaded, it will be returned to the initiator of the delegate, and it will load the class in the specified FILE system or network URL.
If none of them are loaded into the class, a ClassNotFoundException is thrown. Otherwise, the found Class generates a Class definition, loads it into memory, and returns an in-memory Class instance object of the Class.
2. Why use parental delegation?
Because this avoids double loading, there is no need for the child ClassLoader to load the class again when the parent has already loaded the class.
For security reasons, we can imagine that without this delegate pattern, we could use a custom String to dynamically replace the type defined in the Java core API at any time. This would be a huge security risk. Since strings are already loaded by the Bootstrcp ClassLoader at startup, a user-defined ClassLoader will never load a self-written String unless you change the default algorithm for ClassLoader searching classes in the JDK.
3. But how does a JVM determine that two classes are the same when searching for them?
When determining whether two classes are identical, the JVM determines not only whether they have the same class name, but also whether they are loaded by the same classloader instance.
The JVM considers two classes to be the same only if they both satisfy. Even if two classes are the same class bytecode, if they are loaded by two different ClassLoader instances, the JVM will treat them as two different classes.
Such as a Java class ClassLoaderSimple org.classloader.simple.Net on the network, after the javac compiler to generate the bytecode file NetClassLoaderSimple. Class, ClassLoaderA and ClassLoaderB these two class loaders and read the NetClassLoaderSimple. Class files, and define the Java respectively. Lang. To represent the class, the class instance for the JVM, they are two different instance objects, They are really the same bytecode file, if you try to put this Class instance to generate specific object transform, Java runtime exception will be thrown. Lang. ClassCaseException, suggest they are two different types.
Android class loader
For Android, the final APK file contains files of the dex type. The dex file repackages the class file. The packing rules are not simply compressed, but completely optimize the various function tables and change tables inside the class file to generate a new file, namely the dex file. So loading this special Class file requires a special Class loader, DexClassLoader.
4. What are the specific implementation classes of set framework, list, map and set? What are the differences?
1.List and Set inherit from Collection interface, Map does not;
2.List features: elements can be placed in order, and elements can be repeated;
The position of the elements in a Set is determined by the element’s HashCode. Objects added to a Set must define equals().
In addition, list supports for loop, that is, traversal by subscript, can also use iterators, but set can only use iteration, because it is unordered, can not use subscript to get the desired value).
3.Set and List
Set: It is inefficient to retrieve elements, but efficient to delete and insert elements. Insert and delete elements do not change their positions.
List: Like an array, a List can grow dynamically. It is efficient to find elements, but inefficient to insert and delete elements, because it causes other elements to change positions.
4.Map is suitable for storing key-value pair data.
5. Thread-safe and non-thread-safe collection classes
LinkedList, ArrayList, and HashSet are thread-safe; Vector is thread-safe;
HashMap is thread-safe, HashTable is thread-safe;
StringBuilder is not thread-safe, StringBuffer is thread-safe.
Here’s how to use these classes:
Differences between ArrayList and LinkedList and applicable scenarios
Arraylist:
Advantages: ArrayList implements a data structure based on a dynamic array. Because the addresses are contiguous, the query operation is efficient once the data is stored (it is contiguous in memory).
Disadvantages: Because addresses are contiguous, ArrayList moves data around, so insert and delete operations are inefficient.
LinkedList:
Advantages: LinkedList is based on the data structure of LinkedList, and the address is arbitrary, so there is no need to wait for a continuous address when creating memory space. For add and remove operations, LinedList has the advantage. LinkedList is suitable for scenarios where you want to start and end operations or insert a specific location.
Cons: Query performance is low because LinkedList moves Pointers.
Application scenario analysis:
ArrayList is used when data needs to be accessed, and LinkedList is used when data needs to be added and deleted multiple times.
Differences between ArrayList and Vector and applicable scenarios
ArrayList has three constructors:
Public ArrayList(int initialCapacity)// constructs an empty list with a specified initialCapacity. Public ArrayList()// Constructs an empty list of initial capacity 10. public ArrayList(Collection<? Extends E> c)// Constructs a list of elements for the specified collection
Copy the code
A Vector has four constructors:
Public Vector() // Constructs an empty Vector with the specified initial capacity and a capacity increment equal to zero. Public Vector(int initialCapacity) // Constructs an empty Vector with the size of its internal data array, whose standard capacity increment is zero. public Vector(Collection<? Extends E> c) extends E> c) extends E> c) extends E> c) extends E> c) extends E> c) extends E> c CapacityIncrement constructs an empty vector with the specified initial capacity and capacityIncrement
Copy the code
ArrayList and Vector are both implemented using arrays, with three main differences:
1).Vector is multithread safe. Thread-safe means that multiple threads accessing the same code will not produce uncertain results. ArrayList does not. As can be seen from the source code, many of the methods in the Vector class are modified by synchronized, so that Vector cannot compare with ArrayList in efficiency.
2). Both classes use linear continuous space to store elements, but when space is insufficient, the two classes increase in different ways.
3).Vector can set growth factors, whereas ArrayList cannot.
4).Vector is an old dynamic array that is thread synchronized. It is inefficient and generally deprecated.
Applicable scenarios:
1.Vector is thread-synchronous, so it is thread-safe, whereas ArrayList is thread-asynchronous and unsafe. Without regard to thread safety, ArrayList is generally more efficient.
2. If the number of elements in the collection is greater than the size of the current array, using a Vector has certain advantages when using a large amount of data in the collection.
Application scenarios of HashSet and Treeset
1.TreeSet is implemented by binary tree (tree data structure of red-black tree). Data in TreeSet is automatically sorted and null values are not allowed.
2. A HashSet is implemented by a hash table. The data in a HashSet is unordered and can be put into a NULL, but only one NULL.
3. A HashSet requires that objects that have been put into a HashSet must implement the HashCode() method. Objects that have been put into a HashSet are identified by a HashCode, while String objects that have the same content have the same HashCode. But objects of the same class can fit into different instances.
Application scenario analysis:
A HashSet is implemented based on a Hash algorithm and generally performs better than TreeSet. For sets designed for quick lookups, we should usually use hashSets, and TreeSet is used only when we need sorting capabilities.
Differences between HashMap, TreeMap, and HashTable and application scenarios
HashMap is not thread-safe
HashMap: Implementation based on hash table (hash table). The key classes required to be added using HashMap explicitly define hashCode() and equals()[you can override hashCode() and equals()], and you can tune the initial capacity and load factor to optimize the use of HashMap space. There are two kinds of conflict handling of hash table, one is open addressing method and the other is linked list method. The implementation of HashMap uses a linked list method.
TreeMap: Non-thread-safe implementation based on red-black trees. TreeMap has no tuning options because the tree is always in equilibrium.
Application scenario analysis:
HashMap and HashTable:HashMap removes the contains methods of HashTable, but adds containsValue() and containsKey() methods. HashTable is synchronous, whereas HashMap is asynchronous and is more efficient than HashTable. A HashMap allows empty key values, whereas a HashTable does not.
HashMap: Used to insert, delete, and locate elements in a Map.
Treemap: Applies to traversing keys in natural or custom order.
(PS: Actually, we frequently use collections in our work. If you pay attention to them and summarize them, you will be able to answer them easily in the interview.)
5. ConcurrentHashmap principle, atomic class.
ConcurrentHashMap is a thread-safe and efficient HashTable solution, especially the “segment locking” solution, which provides a significant performance improvement over the full table locking of HashTable.
Vi. The principle of volatile
In Concurrent Programming in Java: We’ve covered visibility, ordering, and atomicity in the Core Theory, and you can usually use the Synchronized keyword to solve these problems. But if you know anything about the principle of Synchronized, you know that Synchronized is a heavyweight operation. It has a significant impact on system performance, so we generally avoid using Synchronized to solve the problem if there are other solutions.
The volatile keyword is another solution to visibility and ordering problems provided in Java. One important and often misunderstood point about atomicity is that atomicity is guaranteed by a single read/write on volatile variables, such as long and double, but not by a single read/write on i++, which is essentially read/write.
Refer to the article insert good eye to wait for transmission
https://www.cnblogs.com/paddix/p/5428507.html
Seven. Multithreading usage scenarios
Is it efficient to use multiple threads? Sometimes multithreading is used not to improve efficiency, but to enable the CPU to process multiple events simultaneously.
1). In order not to block the main thread, start other threads to do good things, such as time-consuming operations in the APP are not done in the UI.
2). Implement faster applications, that is, the main thread is dedicated to listening for user requests, and the sub-thread is used to process user requests to achieve large throughput. It seems that multithreading may not be efficient in this case. The purpose of multithreading in this case is to process multiple pieces of data in parallel without waiting.
JavaWeb, for example, has a main thread that listens for HTTP requests and then starts a child thread to process them.
3). A low-priority service that is not performed regularly.
For example, garbage collection for the Jvm.
4.) Some tasks, although time-consuming, but does not consume CPU operation, open multiple threads, efficiency will be significantly improved.
Like reading a file and processing it. Disk IO is a time – consuming, CPU – free effort. So one thread can read the data and one thread can process the data. It’s certainly more efficient than one thread reading the data and then processing it. Because two threads take full advantage of the idle CPU time waiting for disk I/O.
JAVA constant pool
128 of Interger (128 ~ 127)
A. When the value ranges from -128 to 127: If two new objects have the same value, the result is false by “==”, but the result is true by “==”, which is very similar to String.
B. When the value is not in the range of -128 to 127, the result is false even if the two objects have the same value.
C. When an Integer object is directly compared with an int base datatype by “==”, the result is the same as in the first point.
D. Integer Object hash value is the value itself;
Why is it minus 128 minus 127?
The Integer class has a static inner class, IntegerCache, and an Integer array in the IntegerCache class to cache Integer objects in the range -128 to 127.
A brief introduction to generics, generic erasure and related concepts in Java.
Generics are a new feature in Java SE 1.5. The nature of generics is parameterized typing, which means that the data type being operated on is specified as a parameter. This parameter type can be used in the creation of classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively. The benefit of the introduction of generics into the Java language is security and simplicity.
Prior to Java SE 1.5, parameters were “arbitrary” by referring to the type Object in the absence of generics. The disadvantage of “arbitrary” was to do explicit casts that required the developer to be able to predict the actual parameter types. In the case of a cast error, the compiler may not give an error until runtime, which is a security risk.
The benefit of generics is that type safety is checked at compile time, and all casts are automatic and implicit, increasing code reuse.
1. The type parameters of a generic type can only be class types (including custom classes), not simple types.
2. There can be multiple versions of the same generic (because parameter types are indeterminable), and different versions of generic class instances are not compatible.
3. Generics can have more than one type parameter.
4. Generic parameter types can use extends statements, such as <T extends superClass >. It is conventionally called a bounded type.
Parameter types of generics can also be wildcard types. Such as Class <? > classType = Class.forName(“java.lang.String”);
Generic erasure and related concepts
Generics in Java are basically implemented at the compiler level. The type information in generics is not contained in the generated Java bytecode. Type parameters added when using generics are removed by the compiler at compile time. This process is called type erasure.
Type erasure problems and solutions
1. Check first, before compiling, and check compiled objects and reference passing problems
Automatic type conversion
3. Conflicts between type erasure and polymorphism and solutions
4. Generic type variables cannot be primitive data types
5. Runtime type query
6. Problems with using generics in exceptions
7. Arrays (this is not a type erasure problem)
Conflicts after type erasure
10. Problems with generics in static methods and classes
4
I. Handler mechanism
The Android messaging mechanism is also known as the Handler mechanism. When creating a handler, a looper is created (via looper.prepare()). Looper is usually created for the main thread.
The handler sends a message (sendMessage), and of course the post series of methods is also implemented through SEND, in which the handler passes through the enqueueMessage() method EnqueueMessage (MSG,millis) inserts a message to MessageQueue and passes its own handler through MSG. Target = this.
Looper is an infinite loop, constantly reading messages in MessageQueue. The loop method will call the next method of MessageQueue to get new messages. The next operation is a blocking operation, and when there is no message, the next method will always block, thus causing The loop blocks all the time, and Looper processes the message when it receives it: MSG. Target. DispatchMessage (MSG), and of course the MSG here. The target is to pass the above to send this message handler object, so the handler The handler dispatchMessage method is executed in the Looper used to create the handler, thus successfully switching the code logic to the main thread.
The Handler checks if the Message’s callback is null. If it is not null, the Handler processes the Message via handleCallBack. The Message’s callback is a Runnable Object, which is actually a Runnable argument passed by the Handler’s POST method. The second is to check if mCallback is null and then call mCallback’s handleMessage method to process the message.
2. Drawing process of View
OnMeasure() — >OnLayout() — >OnDraw()
Main tasks of each step:
OnMeasure () :
Measure view size. The measure method is recursively called from the top-level parent View to the child View, and the measure method calls back to the OnMeasure.
OnLayout () :
Locate the View and layout the page. The process of recursively calling the view.layout method from the top-level parent View to the child View, that is, the parent View puts the child View in the appropriate position according to the layout size and layout parameters obtained by measure child View in the previous step.
Ontouch () :
Draw the view :ViewRoot creates a Canvas object and calls OnDraw(). Six steps: 1. Draw the background of the view; ② save the Layer of the canvas; ③ Draw the content of the View; (4) Draw a sub-view of the View, if there is no use; ⑤, restore Layer; ⑥ draw the scroll bar.
3. Event transmission mechanism
1). The essence of The Android event distribution mechanism is to solve: which object the click event is emitted from, which object it passes through, which object it finally reaches and finally gets processed. The objects here are activities, viewGroups, and Views.
Activity (Window) -> ViewGroup -> View
3). The event distribution process is assisted by dispatchTouchEvent(), onInterceptTouchEvent() and onTouchEvent()
Set Button Button to respond to click events (as shown below)
The layout is as follows:
The outermost layer Activiy A contains two sub-Views: ViewGroup B and View C
Middle layer: ViewGroup B, containing a child View: View C
Innermost layer: View C
Suppose the user first touches a point on View C on the screen (the yellow area in the figure), the Action_DOWN event is generated at that point, then the user moves his finger and finally leaves the screen.
Button click events:
The DOWN event is passed to C’s onTouchEvent method, which returns true to handle the event;
Since C is processing this event, the DOWN event will no longer be passed up to B and A’s onTouchEvent();
Other events in the event column (Move, Up) will also be passed to C’s onTouchEvent();
(Remember the order of transmission of this diagram, when the interview can draw, it is very detailed)
4. Binder mechanism
1. Understand the Binder
In Android, each application runs in a separate process, which ensures that an exception in one application does not affect the other. In many cases, our activities will interact with various system services. Obviously, we will write programs in which the activity and the system service are not the same process, but how do they communicate with each other?
Binder is one of the ways to implement interprocess communication (IPC) in Android.
1). First, Binder is divided into Client and Server processes.
Note that Client and Server are relative. Whoever sends the message is the Client, and whoever receives the message is the Server.
For example, process A and PROCESS B communicate with each other using Binder. Process A sends messages to process B. Process A is A Binder Client and process B A Server. Process B sends messages to process A, and then B is A Binder Client and A is A Binder Server.
2). Secondly, we see the following figure (from Tian’s blog), which basically explains the composition of Binder:
IPC in the figure stands for interprocess communication.
The ServiceManager in the figure is responsible for registering Binder Server with a container.
The ServiceManager has been likened to a telephone office, storing landline phones in every house, and it is appropriate. If John calls Li Si and dials the number, he will be transferred to the telephone office first. The telephone office operator finds out the address of the number, because Li Si’s number has been registered in the telephone office before, so he can dial the number. If you do not register, you will be prompted that the number does not exist.
According to the Android Binder mechanism, Binder Client is Binder Client, Binder Server is Binder Server, and Telephone office is ServiceManager. Telephone office operators do a lot of things in this process, corresponding to the Binder driver in the figure.
3). Next, we look at the communication process of Binder, again from a picture of Tian’s blog:
Note: SM in the figure is also a ServiceManager.
As you can see, the Client cannot call Server add directly because they are in different processes. Binder is needed.
First, the Server is registered in the SM container.
Secondly, if the Client wants to call the Server add method, it needs to get the Server object first. However, SM does not return the real Server object to the Client. Instead, SM returns a Proxy object of the Server to the Client, namely the Proxy.
Then, the Client calls the Proxy’s Add method, SM calls the Server’s Add method for him, and returns the result to the Client.
Binder drives a lot of the above three steps, but we don’t need to know the underlying implementation of Binder drives, which involves C++ code – limited time to do more meaningful things.
(PS: the above excerpt from bao Jianqiang’s article point me point me).
http://www.cnblogs.com/Jax/p/6864103.html
2. Why Does Android use Binder to implement interprocess communication?
1). Reliability. On mobile devices, the communication mode based on Client-Server is usually used to realize the internal communication between the Internet and devices. Currently, Linux supports IPC including the traditional pipe, System V IPC, namely message queue/shared memory/semaphore, and socket only supports client-server communication. Android system for developers to provide rich interprocess communication function interface, media playback, sensors, wireless transmission.
These functions are managed by different servers. Developers are only concerned with establishing communication between their application’s client and server to use the service. There is no doubt that the complexity of the system is increased if a set of protocols are set up at the bottom layer to implement client-server communication. Implementing this complex environment on a mobile phone with limited resources is difficult to guarantee reliability.
2). Transmission performance. Socket is mainly used for inter-process communication across the network and between processes on the local computer, but the transmission efficiency is low and the cost is high. Message queues and pipes are store-and-forward, in which data is copied from the sender cache to a block of cache created by the kernel, and then copied from the kernel cache to the receiver cache at least twice. Although shared memory does not require copying, it is complicated to control. Compare the number of data copies in various IPC modes. Shared memory: 0 times. Binder: 1 time. Socket/ pipe/message queue: 2 times.
3). Security. Android is an open platform, so keeping your applications secure is important. Android assigns a UID/PID to each installed application, where the process’s UID is used to identify the process. Traditional data packets can only be filled in by the user UID/PID, which is not reliable and easy to be used by malicious programs. We want the kernel to add a reliable UID.
So, for reliability, transmission, security. Android establishes a new way to communicate between processes.
Five. Android process level, and their differences.
1. Foreground processes
This process is required for what the user is currently doing. A process is considered a foreground process if one of the following conditions is met:
1). The process has an Activity that is interacting with the user (the Activity’s onResume() method is called).
2). The process has a Service bound to the activity with which the user is interacting.
3). This process has a foreground running Service (Service calls method startForeground()).
4). This process has a Service that is executing any of its lifecycle callback methods (onCreate(),onStart(), or onDestroy()).
5). This process has BroadcastReceiver that is executing its onReceive() method.
Typically, there are very few foreground processes in existence at any one time. They are killed only when they reach an untunable contradiction — such as when memory is too small to continue running. Typically, by this point, the device has reached a paging scheduling state, so some foreground processes need to be killed to keep the user interface responsive.
2, visible process
A process does not own the components running in the foreground, but can still affect what the user sees. A process is visible when the following conditions are met:
This process has an Activity that is not in the foreground but is still visible (its onPause() method is called). This happens when a foreground activity starts a dialog.
3. Service process
A visible process is considered extremely important. And you can’t touch it unless you have to kill it to keep all foreground processes running.
This process has a Service bound to the visible activity.
A process that is not one of these two is running a service started by startService().
Although a server process does not directly affect what the user sees, it usually does something that the user cares about (such as playing music or downloading data), so the system does not kill the foreground and visible processes if they fail to survive.
4. Background processes
A process has an activity that is not currently visible (the activity’s onStop() method is called).
Such processes do not directly affect the user experience, so the system can kill them at any time to provide storage space for foreground, visual, and server processes. There are usually many background processes running. They are stored in an LRU(least recently used) list to ensure that processes with recently seen activities are killed last. If an activity implements its lifecycle methods correctly and preserves its current state, killing its process will have no impact on the user’s visual experience. Because when the user returns to the activity, the activity restores all of its visible states.
5. Empty processes
A process does not own any active components.
The only reason to keep this kind of process is caching, which improves startup speed the next time a component wants to run it. Systems often kill process caches in order to balance overall system resources between them and the underlying kernel caches.
6. Knowledge about thread pools.
Thread pools in Android are thread pools that implement different features between or indirectly through the configuration of ThreadPoolExecutor. The four most common types of thread pools with different features in Android are FixThreadPool, CachedThreadPool, SingleThreadPool, and ScheduleThreadExecutor.
1).FixThreadPool
Only core threads, and a fixed number of threads, will not be reclaimed. When all threads are active, because the queue size is not limited, new tasks will wait to execute.
Advantages: Faster response to external requests.
2).SingleThreadPool
There is only one core thread, ensuring that all tasks are completed sequentially in the same thread. So you don’t have to deal with thread synchronization.
3).CachedThreadPool
Only non-core threads, the maximum number of threads is very large, when all threads are active, new threads will be created for the new task, otherwise idle threads will be used (60 seconds, the idle time will be reclaimed, so there is a possibility of 0 threads in the thread pool) to process the task.
Advantages: Any task is executed immediately (the SynchronousQueue is equivalent to an empty collection). It is better for performing a large number of small tasks.
4).ScheduledThreadPool
The number of core threads is fixed, and there is no limit to the number of non-core threads (which are immediately recycled when idle).
Advantages: Perform scheduled tasks and repetitive tasks with a fixed period
Android Development – 4 common thread pools in Android (make sure you understand them)
http://blog.csdn.net/seu_calvin/article/details/52415337
Seven. Memory leaks, how to find, how to produce memory leaks.
Memory leaks occur
1). Memory leak caused by resource object not closed
2). No cached convertView is used when the Adapter is constructed
3). Call recycle() to release memory when Bitmap objects are not in use
4). Try to use the application context instead of the activity-related context
5). Memory leak caused by registration not cancelled
6). Memory leaks caused by objects in the collection not being cleaned
Finding memory leaks
Memory leaks can be found using the Android Profiler tool that comes with Android Stdio, or LeadCanary from Square products.
Eight. Android optimization
Performance optimization
1). Use Service sparingly. If an application needs to use a Service to perform background tasks, it should be run only while the task is being executed. When a Service is started, the system tends to reserve the process on which the Service depends. The number of processes that the system can cache in the LRUcache decreases, which costs more performance during program switching. We can use IntentService, which automatically stops when the background task is finished, avoiding the memory leak of Service.
2). Release memory when the interface is not visible. When the user opens another application and the interface is not visible, we should release all resources related to the interface. Override the Activity’s onTrimMemory() method and listen for the TRIM_MEMORY_UI_HIDDEN level in this method. Once triggered, the user has left the program, the resource can be freed.
The onTrimMemory() method has many other types of callbacks that let us know when the phone’s memory is low, and we should decide how to release the application’s resources based on the level passed in the callback.
4). Avoid wasting memory on Bitmap. When reading a Bitmap image, never load resolution that you don’t need. Can compress pictures and other operations.
5). Use optimized data set Android provides a series of optimized data set tool classes, such as SparseArray, SparseBooleanArray, LongSparseArray, using these API can make our program more efficient. The HashMap utility class is relatively inefficient because it needs to provide an object entry for each key-value pair, and SparseArray avoids the time it takes to convert a primitive data type to an object data type.
Layout optimization
1). Reuse layout files
Tags allow the introduction of a layout within a layout, so for example, if all the interfaces of our application have a common section, it is best to extract this common section into a separate layout, and then reference this common section in the layout file of each interface.
Tips: If we want to override the layout property in the tag, we must also override the layout_width and layout_height properties, otherwise the overlay effect will not work.
Tags are used as an auxiliary extension of tags to prevent unnecessary layout nesting when referencing layout files. The more nested the layout, the more time it takes to parse and the worse the performance. So write the layout file with as few nested layers as possible.
For example, use a layout inside a LinearLayout. There is also a LinearLayout inside, so there is actually redundant layout nesting, use merge to solve the problem.
2). Load the layout only when needed
Elements in a layout are not displayed together. In general, only some of the most common elements are displayed, while the less common elements are displayed only when the user performs a specific action.
For example, instead of filling in all the information, there is an option to add more fields. Additional elements are displayed only when the user needs to add additional information. For VISIBLE performance to be mediocre, you can use the ViewStub.
A ViewStub is also a View, but it has no size, no drawing function, and no involvement in layout. It has very low resource consumption and can be considered to have no impact on performance.
Tips: The layout loaded by the ViewStub does not use tags, so this can lead to redundant nested structures in the loaded layout.
High performance coding optimization
It’s all a few minor optimizations, and you don’t see any significant improvement in performance. The use of appropriate algorithms and data structures is the most important means of optimizing program performance.
1). Avoid creating unnecessary objects We should avoid creating unnecessary objects:
If you have strings that need to be concatenated, use StringBuffer or StringBuilder to concatenate strings in preference to the plus concatenator, because using the plus concatenator creates extra objects. The longer the concatenated string, the worse the performance of the plus concatenator.
When a method returns a String, it is often necessary to determine what the String is for. If you know that the caller will concatenate the returned String, consider returning a StringBuffer instead, since this will return a reference to an object. A String creates a temporary object with a short lifetime.
Create as few temporary objects as possible; fewer objects means fewer GC operations.
2). Use primitive data types instead of encapsulated data types for no particular reason. Int is more efficient than Integer, as are other data types.
Arrays of primitive data types are also superior to arrays of object data types. Two other parallel arrays are more efficient than a wrapped array of objects. For example, arrays like Foo[] and Bar[] are much more efficient to use than arrays like Custom(Foo,Bar)[].
3). Static is better than abstract
If you don’t need to access certain fields in a pair and just want to call some of its methods to perform a common function, you can make the method static and call it 15%-20% faster without having to create objects to call it. You don’t have to worry about changing the state of the object when you call this method (static methods can’t access non-static fields).
4). Use static final modifiers for constants
static int intVal = 42; static String strVal = "Hello, world!" ;
Copy the code
The compiler generates an initial method for the above code, called a method, which is called the first time the defined class is used. This method assigns the value of 42 to intVal and a reference from the string constant table to strVal. When the assignment is complete, we can access the specific value through field search.
Final to optimize:
static final int intVal = 42; static final String strVal = "Hello, world!" ;
Copy the code
In this way, you don’t need methods to define classes, because all constants are initialized in the initializer of the dex file. IntVal is called to point directly to the value of 42, while strVal is called in a relatively lightweight string constant rather than a field search.
This optimization only works for primitive data types and String constants, but not for constants of other data types.
5). Use enhanced for loop syntax
static class Counter { int mCount; } Counter[] mArray = ... public void zero() { int sum = 0; for (int i = 0; i < mArray.length; ++i) { sum += mArray[i].mCount; } } public void one() { int sum = 0; Counter[] localArray = mArray; int len = localArray.length; for (int i = 0; i < len; ++i) { sum += localArray[i].mCount; } } public void two() { int sum = 0; for (Counter a : mArray) { sum += a.mCount; }}
Copy the code
Zero () was the slowest, calculating the length of the mArray each Time, one() was much faster, and two()fangfa was the fastest on devices without a JIT(Just In Time Compiler), while one() was Just as efficient on devices with a JIT. Note that this is not supported until JDK1.5.
The handwritten loop of ArrayList is faster than the enhanced for loop, which is not the case with other collections.
So the default is to use an enhanced for loop, while traversing an ArrayList uses a traditional loop.
6). Use more apis packaged by the system
The system can not provide the Api can not complete the function we need to write, because the use of system Api is often much faster than our own code, many of their functions are implemented through the underlying assembly mode.
For example, using a loop to assign values to each element of an array is possible, but using the system.arrayCopy () method is up to nine times faster.
7). Avoid internally calling Getters/Setters methods
The idea of encapsulation in object orientation is not to expose fields inside a class to outsiders, but to provide specific methods that allow outsiders to manipulate fields inside the corresponding class. But in Android, field searches are much more efficient than method calls, and it can be three to seven times faster to access a field directly than to access it via getters.
But writing code is still object-oriented, and we should optimize where we can, such as avoiding internal calls to getters/setters methods.
Ix. Plug-in related technology, how is hot repair technology implemented, and what is the difference between plug-in
Similarities:
All new function classes that use ClassLoader to load can use PathClassLoader and DexClassLoader
Difference:
The hot fix is to fix a Bug, so we need to replace the Bug class with a new class of the same name. We need to load the new class first instead of the Bug class, so we need to do two more things: When the original APP is packaged, relevant classes are prevented from displaying the CLASS_ISPREVERIFIED flag, and dexElements indirectly referenced by the BaseDexClassLoader object are dynamically changed during the hot repair, so as to replace the Bug classes first and complete the system not to load the old Bug classes.
Plugins are just adding new classes or resource files, so they don’t involve preloading old classes. It avoids the dexElements that prevent related classes from marking the CLASS_ISPREVERIFIED flag and dynamically changing indirect references to BaseDexClassLoader objects during hot repair.
Therefore, plug-in is easier than hot repair, hot repair is on the basis of plug-in for the old Bug class
10. How to calculate the size of an image, the process of loading bitmap (how to ensure that there is no memory overflow), two level cache, LRUCache algorithm.
Calculate the size of a picture
Image memory is calculated by the following formula: image height * image width * memory size per pixel. Therefore, when calculating the memory size of the image, we should consider the directory where the image is located and the density of the device. These two factors actually affect the height and width of the image. Android will pull up and compress the image.
Loading bitmap process (how to ensure no memory overflow)
Since Android has a memory limit for images, loading large images that are several megabytes in size can run out of memory. Bitmap will load all pixels of the image (i.e. length x width) into memory. If the image resolution is too large, the memory will directly result in OOM. Only when BitmapFactory loads the image, use bitmapFactory. Options to configure relevant parameters to reduce the load of pixels.
Bitmapfactory. Options Description of related parameters
(1). The Options. InPreferredConfig values to reduce memory consumption.
For example, change the default ARGB_8888 value to RGB_565, saving half of the memory.
(2). Set options. inSampleSize scale to compress large images.
(3). Set options. inPurgeable and inInputShareable to enable the system to retrieve memory in time.
A: inPurgeable: If this parameter is set to True, the system memory can be reclaimed if it is insufficient. If this parameter is set to False, the system memory cannot be reclaimed.
B: inInputShareable: indicates whether to set deep copy. This parameter is used together with inPurgeable. If inPurgeable is false, this parameter is invalid.
(4). Use decodeStream instead of other methods.
DecodeResource setImageResource, setImageBitmap method, etc
11. How to realize LRUCache algorithm.
Internal LinkedHashMap and maxSize, store the recently used objects in LinkedHashMap with strong references, give the put and get methods, calculate the total size of all images in the cache each time put images, compare with maxSize, greater than maxSize. Remove the oldest image; Otherwise less than maxSize is added.
Previously, we used in-memory caching techniques, known as soft or weak references. Starting with Android 2.3 (APILevel 9), garbage collectors tend to recycle objects that hold soft or weak references, making them less reliable.
5
Algorithm problem
M by n matrix, can form how many squares (2 by 2 can form 1 square, 2 by 3 2, 3 by 3 6)
Count the key is to observe any a sloping square is the only inscribed on a sloping square, rather a sloping side length to k of the sloping square, a side has k – 1 point, each interior point to determine a tilted inscribed in the square, and the tilt the square itself, Multiply the number of non-tilted squares with sides of length K by k and sum by k to obtain the total number of squares.
If 2≤n≤m, k≤n-1, then there are non-inclined ones with side length K
N minus k times m minus k, so all squares have
∑ (m – k), k (n, k)
For example, m = n = 4
There are 331+222+113=20 squares.
6
The answers to most questions can be found on it.
Telephone interview questions
ArrayList and Hashmap A few words about the differences between the underlying data structures.
2.Handler Message mechanism
3. Memory leak scenario
4. Multi-threaded usage scenarios?
5. What are the common thread pools?
6. What did you do in the company? Team size? Why did you leave?
The first round
1. Know which singleton patterns, write a thread-safe singleton, and analyze why it is thread-safe?
2. What are the collections in Java? Explain HashMap? The data structure at the bottom? Hash table conflict handling method, what is a hash table data structure? What approach does HashMap take to handle conflicts?
3. Explain what the MVP architecture is, draw a diagram and explain the difference between MVP and MVC in one sentence.
4.Handle message mechanism? What are some things to look out for when using handlers, and do they cause memory leaks? How do I draw a diagram of the Handler mechanism?
5. Has performance optimization been performed? What steps have been taken to optimize?
6. What is the cause of the memory leak? And how did you solve it?
These questions should be fairly basic, and every developer should be familiar with them and able to describe them in detail. This round of interviewers are asking about the usual techniques.
The second round
1. How much do you understand concurrency? How many concurrent sets?
2.Handler message mechanism diagram?
3. What did you do in the project?
4. Draw a picture to illustrate the View event transfer mechanism. And give an example to illustrate
5. Class loading mechanism, how to skin, problems existing in skin plug-in? Have you used hotfix before and understand its principle?
6. Describe the design patterns used in the project, including the strategic and observer patterns.
7. Can you play JS? Do you have experience in Hybid development?
8. What about the idea of quicksort? Handwritten code
9. What data structures does the heap have?
For this round surface, she obviously felt pressure and had a deep vertical understanding of knowledge, so she should be a leader.
In the third round
1. Describe your role in the project?
2. How did you solve the difficulties?
3. How to get along with others and how to solve the disagreement with others? Cite an example from your life.
4. Was there a particularly stressful time?
This should be the project manager, ask questions tend to life personality.
The questions asked above in the interview basically can find the answer above, so it is very important to prepare, but the technology is a little bit of accumulation, even if you plenary back, the interview, really wait until the work will still be short of money, so practical point SAO years.
Recommended reading:
Will know will be | Android in aspects of performance optimization are here
Recommend several quality complete projects to study
Android courses jointly developed by Google, Didi and Udacity include a hands-on project from Silicon Valley, one-on-one code reviews and technical guidance. Some of the courses are now available for free, and those interested can scan the QR code below.