In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the high-level Android interview questions?" in the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. The difference between = = and equals and hashCode in java
The values of the = = comparison of the basic data types are equal.
The address of the memory of the class = =, that is, whether it is the same object or not, the original implementation is also = = without overwriting equals. For example, String overrides the equals method.
HashCode is also a method of the Object class. Returns a discrete int integer. Used in collection class operations to improve query speed. (whether HashMap,HashSet and other comparisons are the same)
If two objects equals,Java the runtime environment will assume that their hashcode must be equal.
If two objects are not equals, their hashcode is likely to be equal.
If two objects are equal in hashcode, they are not necessarily equals.
If the hashcode of two objects is not equal, they must not be equals.
2. The difference between int and integer
Int basic types
The wrapper class of the integer object int
3. The difference between String, StringBuffer and StringBuilder
String: string constants are not suitable for frequently changing worthwhile situations. Each change is equivalent to generating a new object.
StringBuffer: string variable (thread safe)
StringBuilder: string variable (thread unsafe) ensures availability in a single thread and is slightly more efficient than StringBuffer
4. What is the inner class? The role of the inner class
The inner class can directly access the properties of the external class.
Inner classes in Java are mainly divided into member inner classes, local inner classes (nested in methods and scopes), anonymous inner classes (no constructed methods), and static inner classes (static modified classes, which cannot use non-static member variables and methods of any peripheral classes, and do not rely on peripheral classes).
5. The difference between process and thread
The process is the smallest unit of cpu resource allocation and the thread is the smallest unit of cpu scheduling.
Resources cannot be shared between processes, while threads share the address space and other resources of their processes.
There can be multiple threads in a process, and the process can start the process or the thread.
A thread can only belong to one process, the thread can directly use the resources of the same process, and the thread depends on the process.
6. The difference of final,finally,finalize
Final: decorate classes, member variables and member methods. Classes are not inheritable, member variables are immutable, and member methods are not rewritable
Finally: with try...catch... Use it together to ensure that it can be called to the
Finalize: the method of the class, which is called before garbage collection. The subclass can override the finalize () method to reclaim resources.
7. The difference between Serializable and Parcelable
The Serializable Java serialization interface generates a large number of temporary variables in the process of reading and writing on the hard disk, and performs a large number of iUnix operations internally, which is very inefficient.
Parcelable Android serialization interface is efficient and troublesome to read and write in memory (AS has a method for one-click generation of related plug-ins), and objects cannot be saved to disk.
8. Can static properties and static methods be inherited? Can it be rewritten? And why?
Inheritable, not rewritten, but hidden.
If static methods and properties are defined in a subclass, then the static methods or properties of the parent class are called "hidden". If you want to call the static methods and properties of the parent class, go directly through the parent class name. The method or variable name is complete.
9. Understanding of member inner class, static inner class, local inner class and anonymous inner class, as well as application in the project
Inner classes in ava are mainly divided into member inner classes, local inner classes (nested in methods and scopes), anonymous inner classes (no constructed methods), and static inner classes (static modified classes, which cannot use non-static member variables and methods of any peripheral classes, and do not rely on peripheral classes).
The most attractive reason for using inner classes is that each inner class can inherit an implementation independently, so whether or not the outer class inherits an implementation has no effect on the inner class.
Because Java does not support multiple inheritance, it supports the implementation of multiple interfaces. But sometimes there are some problems that are difficult to solve with interfaces. At this time, we can use the ability of internal classes to inherit multiple concrete or abstract classes to solve these programming problems. It can be said that interfaces only solve part of the problem, while inner classes make the solution of multiple inheritance more complete.
10. The way and principle of converting string to integer
String integer Intrger.parseInt (string)
Integer string Integer.toString ()
11. under what circumstances will objects be disposed of by the garbage collection mechanism?
1. None of the instances are accessed by active threads.
two。 A circular reference instance that is not accessed by any other instance.
There are different reference types in 3.Java. Determining whether an instance meets the criteria for garbage collection depends on its reference type.
To judge what kind of object is useless. Here are two ways:
1. Using the method of tag counting:
Mark the object in memory, the object is referenced once, the count is increased by 1, the reference is released, the count is reduced by 1, and when the count is 0, the object can be recycled. Of course, this gives rise to a problem: circular referenced objects are unrecognized and recycled. So there is a second way:
two。 Use the root search algorithm:
Starting from a root, search for all reachable objects so that the remaining objects need to be recycled
12. What is the difference between static agents and dynamic agents?
Static proxy class:
The source code is created by a programmer or automatically generated by a specific tool and then compiled. The .class file for the agent class already exists before the program runs. Dynamic proxy class: dynamically created by using reflection mechanism when the program is running.
14. What is the mechanism for implementing polymorphism in Java?
A: method rewriting Overriding and overloading Overloading are different manifestations of Java polymorphism.
Rewriting Overriding is a manifestation of polymorphism between parent and subclass
Overloading Overloading is a manifestation of polymorphism in a class.
16. Tell me about your understanding of Java reflection
JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of that class; for any object, you can call any of its methods and properties. Starting from the object, you can get the complete information of the class through reflection (Class class) (class name Class type, package, all method Method [] types it has, complete information of a method (including modifiers, return value types, exceptions, parameter types), all properties Field [], complete information of a property, constructor Constructors) Call the class's properties or method's own summary: get all the information about the class, object, and method during the run.
17. Tell me about your understanding of Java comments
Meta annotation
The role of meta-annotations is to be responsible for annotating other notes. When java5.0, four standard meta-annotation types are defined, which are used to describe the types of other annotations.
1.@Target
2.@Retention
3.@Documented
4.@Inherited
18. Understanding of String in Java
In the source code, string is decorated with final, which is an immutable, non-inherited constant.
19. Why is String designed to be immutable?
1. Requirements for string pools
A string pool is a special storage area in the method Method Area. When a string has been created and the string is in the pool, the reference to the string is immediately returned to the variable, rather than recreating a string and returning the reference to the variable. If the string is not immutable, changing the string of one reference (such as: string2) will cause dirty data to appear in another reference (such as: string1).
2. Allow strings to cache hash codes
The hash code of a string is often used in java, such as HashMap. The invariance of String ensures that the hash code is always the same, so he doesn't have to worry about changes. This approach means that you don't have to recalculate the hash code every time you use it-- it's much more efficient.
3. Security
String is widely used for parameters in java classes, such as network connection (Network connetion), open file (opening files), and so on. If String is not immutable, network connections and files will be changed-which will lead to a series of security threats. The method of operation thought it was connected to a machine, but in fact it was not. Because the parameters in the reflection are all strings, it can also cause a series of security problems.
20. Equal and hashCode methods of the Object class are overridden. Why?
First of all, the relationship between equals and hashcode is as follows:
1. If two objects are the same (that is, true is returned by equals comparison), then their hashCode values must be the same
2. If the hashCode of two objects is the same, they are not necessarily the same (that is, false is returned by equals comparison)
Because the hashcode method is implemented in order to improve the efficiency of the program, we first compare the hashcode. If it is different, there is no need to compare the equals, so the number of equals comparisons is greatly reduced. It is obvious that the comparison requires a large amount of efficiency improvement.
21. The difference between List,Set,Map
Set is the simplest collection. The objects in the collection are not sorted in a specific way, and there are no duplicate objects. The Set interface mainly implements two implementation classes: HashSet: 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 to sort objects in the collection.
The characteristic of List is that its elements are stored in a linear manner, and duplicate objects can be stored in the collection.
ArrayList (): represents an array whose length can be changed. Elements can be accessed randomly, and the insertion and deletion of elements into ArrayList () is slow.
LinkedList (): the linked list data structure is used in the implementation. Insert and delete speed is fast, access speed is slow.
Map is a set that maps key objects to value objects, and each element 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 is returned.
HashMap:Map is based on a hash table implementation. The cost of inserting and querying key-value pairs is fixed. The capacity capacity and load factor 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 in which "key-value pairs" are obtained is the order in which they are inserted, or the order in which the least recently used (LRU) is obtained. Only a little slower than HashMap. It is faster during iterative access because it uses linked lists to maintain internal order.
TreeMap: implementation based on red-black tree data structure. When you view "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 the subMap () method, which can return a subtree.
WeakHashMao: objects used in the weak key Map,Map are also allowed to be released: this is designed to solve special problems. If no reference other than map points to a key, the key can be reclaimed by the garbage collector.
26. Comparison between ArrayMap and HashMap
1. Different storage methods
There is a HashMapEntry [] object inside HashMap, and each key-value pair is stored in this object. When you add a key-value pair using the put method, it will new a HashMapEntry object.
2. When adding data, the processing of capacity expansion is different. The new operation is performed and the object is recreated, which is very expensive. ArrayMap uses copy data, so it is relatively efficient.
3. ArrayMap provides the function of array contraction. After clear or remove, the array will be recontracted. Whether it is space or not.
4. ArrayMap uses dichotomy to search.
29. The difference between HashMap and HashTable
1 HashMap is not thread safe, it is more efficient, and the method is not Synchronize. To provide external synchronization, there are containsvalue and containsKey methods.
Hashtable is thread-safe, does not allow keys and values of null, is slightly less efficient, and the method is Synchronize. There are contains methods. Hashtable inherits from the Dictionary class
30. The difference between HashMap and HashSet
HashMap:HashMap implements the Map interface, HashMap stores key-value pairs, uses the put () method to put elements into map, and HashMap uses key objects to calculate hashcode values. HashMap is faster because unique keys are used to get objects.
HashSet implements the Set interface, HashSet only stores objects, uses the add () method to put elements into set, and HashSet uses member objects to calculate hashcode values. Hashcode may be the same for two objects, so the equals () method is used to determine the equality of objects, and returns false if the two objects are different. HashSet is slower than HashMap.
31. How do HashSet and HashMap determine that the collection elements are duplicated?
HashSet cannot add duplicate elements, when the add (Object) method is called
First, the hashCode method of Object is called to determine whether the hashCode already exists, and if it does not exist, the element is inserted directly; if it already exists, the equals method of the Object object is called to determine whether to return true; if it is true, the element already exists; if it is false, the element is inserted.
33. The difference between ArrayList and LinkedList, as well as application scenarios
ArrayList is implemented based on arrays, and ArrayList threads are not safe.
LinkedList is implemented based on double linked lists:
Use the scene:
(1) if the application does a large number of access or delete operations to the elements at each index location, the ArrayList object is much better than the LinkedList object.
(2) if the application mainly loops through the list and inserts or deletes during the loop, the LinkedList object is much better than the ArrayList object.
34. The difference between array and linked list
Array: elements are stored continuously in memory; its advantages: because the data is stored continuously, the memory address is continuous, so it is more efficient to find data; its disadvantages: before storage, we need to apply for a continuous piece of memory space, and we must determine the size of its space when compiling. The size of the space at run time cannot be changed with the increase and decrease of your needs. When the data is larger, it may be out of bounds, and when the data is small, memory space may be wasted. When changing the number of data, the efficiency of adding, inserting and deleting data is relatively low.
Linked list: dynamically apply for memory space. You don't need to apply for memory size in advance like arrays. Linked lists only need to apply for memory when you use it, and dynamically apply or delete memory space as needed. It is more flexible than arrays to add, delete and insert data. In addition, the data in the linked list can be associated with the data through the application at any location in memory (that is, through the pointer of the existing element).
35. Three ways to start a thread?
Ava has three ways to create threads, which are inheriting the Thread class, implementing the Runable interface, and using thread pools
36. What is the difference between threads and processes?
Threads are a subset of processes, and a process can have many threads, each of which performs different tasks in parallel. Different processes use different memory space, while all threads share the same memory space. Don't confuse it with stack memory, each thread has a separate stack memory for storing local data.
38. The difference between run () and start () methods
This question is often asked, but it can tell the interviewer's understanding of the Java threading model. The start () method is used to start the newly created thread, and the run () method is called internally by start (), which is different from calling the run () method directly. When you call the run () method, it will only be called in the original thread, and no new thread will start the start () method will start the new thread.
39. How to control the number of concurrent access threads allowed by a method?
Semaphore.acquire () requests a semaphore, when the number of semaphores is-1 (once there is no semaphore available, that is, when the number of semaphores becomes negative, it will block when requested again until other threads release the semaphore)
Semaphore.release () releases a semaphore, and the number of semaphores is + 1
40. The difference between wait and seelp methods in Java
Both wait and sleep in Java programs cause some form of pause that can meet different needs. The wait () method is used for inter-thread communication, releasing the lock if the wait condition is true and other threads are woken up, while the sleep () method simply releases CPU resources or stops the current thread from executing for a period of time, but does not release the lock.
41. Talk about the understanding of wait/notify keyword
Wait for the synchronization lock of the object, and you need to obtain the synchronization lock of the object before you can call this method, otherwise the compilation can pass, but the runtime will receive an exception: IllegalMonitorStateException.
Calling the wait () method of any object causes the thread to block, the thread can no longer execute, and the lock on the object is released.
Wake up the thread waiting for the object's synchronization lock (only one, if more than one is waiting). Note that when this method is called, it does not exactly wake up a waiting thread, but it is up to JVM to determine which thread to wake up, not by priority.
Calling the notify () method of any object causes one of the randomly selected threads blocked by the call to the object's wait () method to unblock (but not really executable until the lock is acquired).
42. What causes thread blocking? How does the thread shut down?
The blocking method means that the program waits for the method to complete and does nothing else, while the accept () method of ServerSocket waits for the client to connect. Blocking here means that the current thread is suspended until the result of the call is returned and will not return until the result is obtained. In addition, there are asynchronous and non-blocking methods that return before the task is completed.
One is to call the stop () method in it.
The other is to set a flag to stop the thread yourself (recommended)
43. How to ensure thread safety?
1.synchronized
Wait,notify in 2.Object method
3.ThreadLocal mechanism to achieve.
44. How to achieve thread synchronization?
1. The method of modifying synchronized keyword. 2. Statement block modified by synchronized keyword. 3. Use special domain variables (volatile) to achieve thread synchronization
45. List for inter-thread operation
List list = Collections.synchronizedList (new ArrayList ())
46. Talk about the understanding of Synchronized keyword, class lock, method lock and reentrant lock
Java object lock and class lock: the concept of java object lock and class lock is basically the same as the built-in lock, but the two locks are actually very different. The object lock is used on the object instance method, or on an object instance, and the class lock is used on the static method of the class or on the class object of a class. We know that there can be many object instances of a class, but each class has only one class object, so the object locks of different object instances do not interfere with each other, but each class has only one class lock. But it must be noted that in fact, class lock is only a conceptual thing, not real, it is only used to help us understand the difference between locking instance methods and static methods.
49. The difference between synchronized and volatile keywords
1.volatile essentially tells jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from main memory; synchronized locks the current variable so that only the current thread can access it, and other threads are blocked.
2.volatile can only be used at the variable level; synchronized can use the
3.volatile can only realize the modification visibility of variables, but can not guarantee atomicity, while synchronized can guarantee the visibility and atomicity of variables.
4.volatile does not cause thread blocking; synchronized may cause thread blocking.
Variables marked by 5.volatile are not optimized by the compiler; variables marked by synchronized can be optimized by the compiler
51, ReentrantLock, synchronized and volatile comparison
For a long time in the past, ava can only be mutually exclusive through the synchronized keyword, but it has some disadvantages. For example, you can't extend methods or block boundaries outside the lock, and you can't cancel when you try to acquire the lock. Java 5 provides more complex control to solve these problems through the Lock interface. The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized, and it is also extensible.
53. the four necessary conditions for deadlock?
The cause of deadlock
1. Competition of system resources
The competition of system resources leads to insufficient system resources and improper allocation of resources, which leads to deadlock.
two。 The process runs in an inappropriate order.
Mutually exclusive condition: a resource can only be used by one process at a time, that is, a resource is occupied by only one process for a period of time. At this point, if another process requests the resource, the requesting process can only wait.
Request and retention condition: the process has maintained at least one resource, but a new resource request has been made, and the resource has been occupied by other processes, when the requesting process is blocked, but does not let go of the resources it has acquired.
Inalienable condition: the resource obtained by the process cannot be forcibly taken away by other processes until it has been used up, that is, it can only be released by the process that acquired the resource itself (can only be released actively).
Loop wait condition: the relationship between several processes that form a head-to-tail loop waiting resource
These four conditions are the necessary conditions of deadlock, as long as deadlock occurs in the system, these conditions must be established, and as long as one of the above conditions is not met, deadlock will not occur.
Deadlock avoidance and prevention:
The basic idea of deadlock avoidance:
The system dynamically checks each resource request that the process can meet, and decides whether to allocate resources according to the inspection results. If the system may have a deadlock after allocation, it will not be allocated, otherwise it will be allocated. This is a dynamic strategy to ensure that the system does not enter the deadlock state.
By understanding the causes of deadlocks, especially the four necessary conditions for deadlocks, deadlocks can be avoided, prevented and released as much as possible. Therefore, in the aspects of system design and process scheduling, we should pay attention to how to make these four necessary conditions not established, and how to determine the reasonable allocation algorithm of resources so as to prevent the process from occupying system resources permanently. In addition, prevent the process from consuming resources while in a waiting state. Therefore, reasonable planning should be given to the allocation of resources.
The difference between deadlock avoidance and deadlock prevention:
Deadlock prevention is to try to destroy at least one of the four necessary conditions to produce deadlocks, strictly prevent the occurrence of deadlocks, while deadlock avoidance is not so strict to limit the existence of the necessary conditions for deadlocks, because even if the necessary conditions for deadlocks exist, deadlocks don't necessarily occur. Deadlock avoidance is to avoid the final occurrence of deadlock during the operation of the system.
What is a thread pool and how to use it?
It takes expensive resources and time to create a thread, it takes longer to create a thread if the task comes, and the number of threads that a process can create is limited. To avoid these problems, several threads are created to respond to processing when the program starts. They are called thread pools, and the threads in them are called worker threads. Starting with JDK1.5, Java API provides an Executor framework that allows you to create different thread pools. For example, a single thread pool handles one task at a time; a fixed number of thread pools or cached thread pools (an extensible thread pool for programs with many short-lived tasks).
57. What's the difference between heap and stack in Java?
Why is this question classified as multithreaded and concurrent interview questions? Because the stack is an area of memory that is closely related to threads. Each thread has its own stack memory for storing local variables, method parameters, and stack calls, and variables stored in one thread are invisible to other threads. The heap is a common area of memory shared by all threads. Objects are created in the heap, in order to improve efficiency, the thread will get a cache from the heap to its own stack, if multiple threads use this variable may cause problems, then the volatile variable can play a role, it requires the thread to read the value of the variable from main memory.
58. There are three threads, T1, T2, T3, how to ensure that they are executed sequentially?
In multithreading, there are several ways for threads to execute in a specific order. You can use the thread class's join () method to start another thread in one thread, and another thread finishes the thread to continue execution. To ensure the order of the three threads, you should start the last one first (T3 call T2 T2 call T1) so that T1 completes first and T3 finishes last.
Inter-thread communication
We know that threads are the smallest unit of CPU scheduling. In Android, the main thread cannot do time-consuming operations, and child threads cannot update the UI. There are many ways to communicate between threads, such as broadcast, Eventbus, interface drop, and handler is mainly used in Android. Handler sends the Message that saves the message to Messagequeue by calling the sendmessage method, while the looper object constantly calls the loop method, takes the message from the messageueue and gives it to handler for processing, thus completing the communication between threads.
Thread pool
There are four common thread pools in Android: FixedThreadPool, CachedThreadPool, ScheduledThreadPool, and SingleThreadExecutor.
The FixedThreadPool thread pool is created through the new FixedThreadPool method of Executors. It is characterized by a fixed number of threads in the thread pool. Even if threads are idle, they will not be recycled unless the thread pool is closed. When all threads are active, the new task is queued for the thread to process. Note that FixedThreadPool has only core threads, not non-core threads.
The CachedThreadPool thread pool is created through Executors's newCachedThreadPool. It is a thread pool with a variable number of threads, it has no core threads, only non-core threads. When all the threads in the thread pool are active, new threads will be created to handle new tasks. Otherwise, idle threads will be used to handle new tasks. All threads in the thread pool have a timeout mechanism, which lasts for 60s, after which idle threads will be reclaimed. This thread pool is suitable for handling a large number of less time-consuming tasks. It has to be said here that the task queue of CachedThreadPool is basically empty.
The Scheduled ThreadPool thread pool is created through Executors's newScheduledThreadPool, whose core threads are fixed, but the number of non-core threads is not fixed, and is recycled as soon as the non-core thread is idle. This kind of thread is suitable for executing scheduled tasks and repetitive tasks with fixed cycles.
SingleThreadExecutor thread pools are created through Executors's newSingleThreadExecutor method, and there is only one core thread and no non-core thread in this thread pool, which ensures that all tasks can be executed in the same thread and in order, so that thread synchronization does not need to be considered.
How AsyncTask works
AsyncTask is a lightweight asynchronous task class provided by Android itself. It can perform background tasks in the thread pool and then pass the progress and final result of the execution to the main thread update UI. In fact, Thread and Handler are encapsulated inside AsyncTask. Although AsyncTask is convenient to perform background tasks and update UI on the main thread, AsyncTask is not suitable for particularly time-consuming background operations, and thread pools are recommended for particularly time-consuming tasks.
AsyncTask provides four core methods:
1. OnPreExecute (): this method is executed in the main thread, is called before the asynchronous task is executed, and is generally used for some preparatory work.
2. DoInBackground (String... Params): this method is executed in the thread pool and is used to perform asynchronous tasks. In this method, you can update the progress of the task through the publishProgress method, the publishProgress method calls the onProgressUpdate method, and the result of the task is returned to the onPostExecute method.
3. OnProgressUpdate (Object... Values): this method is executed in the main thread and is mainly used when the task progress is updated.
4. OnPostExecute (Long aLong): executes in the main thread. After the asynchronous task is executed, the method will be called. The parameters of the method and the result will be returned for the background.
In addition to these methods, there are some less commonly used methods, such as onCancelled (), which are called in the event of an asynchronous task cancellation.
The source code knows that what is called from inside the execute method above is the executeOnExecutor () method, that is, executeOnExecutor (sDefaultExecutor, params); sDefaultExecutor is actually a serial thread pool. The onPreExecute () method will be called here. Then look at this thread pool. The execution of AsyncTask is queued because of the keyword synchronized, and the Params parameter of AsyncTask is encapsulated as a FutureTask class, which is a concurrent class, where it acts as a Runnable. The FutureTask will then be handed over to the SerialExecutor's execute method, and the SerialExecutor's executor method will first add FutureTask to the mTasks queue, and if there is no task at this time, the scheduleNext () method will be called to execute the next task. If there is a task, the scheduleNext (); is finally called after execution. Until all the missions are completed. The constructor of AsyncTask has a call () method, which is executed by the run method of FutureTask. So eventually the call method will be executed in the thread pool. This is where the doInBackground method is called. Let's take a good look at this call () method. MTaskInvoked.set (true); indicates that the current task has already been executed. The doInBackground method is then executed, and finally the result is passed through the postResult (result); method. In the postResult () method, the message is sent through sHandler, and in sHandler, a MESSAGE_POST_RESULT is determined by the type of message, in this case, the onPostExecute (result) method is called or onCancelled (result) is called. The other message type is MESSAGE_POST_PROGRESS, which calls the update progress onProgressUpdate.
The working Mechanism of Binder
Intuitively speaking, Binder is a class in Android, which implements the IBinder interface. From the perspective of IPC, Binder is a way of cross-process communication in Android. At the same time, it can be understood as a virtual physical device, and its device driver is / dev/binder/. From the perspective of Framework, Binder is the bridge of ServiceManager. From the application layer, Binder is the medium of communication between the client and the server.
Let's first look at the meaning of each method in this class:
The unique identity of the DESCRIPTOR:Binder, which is generally used for the class name representation of the current Binder.
AsInterface (android.os.IBinder obj): used to convert the Binder object on the server side into the AIDL interface type object required by the client side. This conversion process distinguishes the process. If the client side and the server side are in the same process, then this method returns the server side stub object itself, otherwise the system encapsulated Stub.proxy object is returned.
AsBinder (): used to return the current Binder object.
OnTransact: this method runs in the Binder thread pool on the server side. When the client initiates a cross-process communication request, the remote request is encapsulated through the system layer and handed over to the method for processing. Note that this method public boolean onTransact (int code, android.os.Parcel data, android.os.Parcel reply, int flags), the server can determine what the target method requested by the client is through code, then extract the parameters required by the target method from the data, and then execute the target method. When the target method is executed, it is like writing the return value in reply. This is how this method is executed. If this method returns false, the client will fail the request, so we can do some security verification in this method.
The working mechanism of Binder but should pay attention to some problems: 1, when the client initiates a request, because the current thread will be suspended until the server returns data, if this remote method is very time-consuming, then it is not possible to initiate this remote request in the UI thread, that is, the main thread.
2. Because Service's Binder method runs in the thread pool, the Binder method should be synchronized whether it is time-consuming or non-time-consuming, because it is already running in a thread.
Event Distribution of view and how view works
Android custom view, we all know that the implementation has a trilogy, onMeasure (), onLayout (), onDraw (). The drawing process of View starts with the perfromTraversal method of viewRoot. It can only draw the view through the measure,layout,draw method. Where measure measures width and height, layout determines the position of view on the parent container, and draw draws view to the screen.
Measure:
The measurement of view requires MeasureSpc (measurement specification), which represents a 32-bit int value, with high 2 bits representing SpecMode (measurement mode) and low (30) bits representing SpecSize (size under a certain measurement mode). On the other hand, a set of SpecMode and SpeSize can be packaged into a MeasureSpec, whereas MeasureSpec can unpack the values of SpecMode and SpeSize. There are three types of SpecMode:
UnSpecified: the parent container has no restrictions on view, as big as it can be. The general system uses this more.
Exactly: the parent container has detected the exact size required by the view. In this case, the size of the view is the value specified by SpecSize, which corresponds to the math_parent or the specific value in the layout layout.
At_most: the parent container specifies that the SpecSize,view of an available size cannot be larger than this value, which corresponds to the wrao_content in the layout.
For a normal view, its MeasureSpec is determined by the parent container's MeasureSpec and its own layoutParam. Once the MeasureSpec is determined, the onMeasure can determine the width and height of the view.
The measure process of View:
The onMeasure method has a setMeasureDimenSion method to set the width and height measurement of the view, while the setMeasureDimenSion has a getDefaultSize () method as a parameter. In general, we only need to pay attention to at_most and exactly. The return value of getDefaultSize is the SpecSize in measureSpec, and this value is basically the measured size of view. In the case of UnSpecified, it is generally a measurement process within the system, and it needs to consider the background of view.
What I said above is the measurement process of view, while the measure process of viewGroup:
For viewGroup, in addition to completing its own measure process, it has to traverse to call the measure method of the subclass. Each child element is recursively executing this process. ViewGroup is an abstract class that does not provide an onMeasure method, but provides a measureChildren method. The idea of the measureChild method is to extract the layoutParams of the child elements, and then use getChildMeasureSpec to see the MeasureSpec of the child elements, and then measure the sub-elements in the electrophoretic measure method. Because the viewGroup subclass has different layouts, resulting in different measurement details, viewGroup cannot call the onMeasure method to measure as view does.
Note: there is no way to correctly obtain the width and height of the activity during the life cycle of the view because the view has not been measured.
Get in the onWindowFocuschanged method-change the method means that view has been initialized
The View.post () method delivers the run side to the end of the message queue.
Use the callback of viewTreeObserver to do this.
It is measured manually by view.measure.
OnLayout
For a normal view, you can get the position of the four vertices of the view through the setFrame method, which determines the position of the view in the parent container, and then calls the onLayout method, which determines the location of the child elements by the parent container.
OnDraw
This method is to draw the view onto the screen. Divide it into the following steps
Draw the background
Draw yourself
Draw child
Draw decorations.
Performance Optimization in Android
Due to the limitations of mobile phone hardware, memory and CPU can not have the same super-large memory as pc. On Android phones, excessive use of memory will easily lead to oom, excessive use of CPU resources will lead to phone stutters, and even lead to anr. I mainly optimize it from the following parts:
Layout optimization, rendering optimization, memory leak optimization, response speed optimization, listview optimization, bitmap optimization, thread optimization
Layout optimization: tool hierarchyviewer, solution:
1. Delete useless spaces and levels.
2. Choose a viewgroup with low performance, such as Relativelayout, and if you can choose Relativelayout or LinearLayout, you will give priority to using LinearLayout, because relatively complex Relativelayout features will take up more CPU resources.
3, use tags to reuse the layout, reduce levels, preload, and load only when you use it.
Rendering optimization
Rendering optimization means that view avoids a large number of time-consuming operations in the ondraw method, because the ondraw method may be called frequently.
1. Do not create new local variables in the ondraw method. The ondraw method is called frequently, which is easy to cause GC.
2. Do not do time-consuming operations in the ondraw method.
Memory optimization: reference memory leaks.
Response optimization
The main thread can not do time-consuming operations, touch event 5s, broadcast 10sbook service20s.
Listview Optimization:
1. Avoid time-consuming operations in the getview method.
2. Reuse of view and use of viewholder.
3. Sliding is not suitable for turning on asynchronous loading.
4. Paging data processing.
5. Pictures use three-level cache.
Bitmap Optimization:
1. Compress the picture in proportion.
2. Recycler unused pictures in time.
Thread optimization
The idea of thread optimization is to use thread pool to manage and reuse threads, to avoid a large number of Thread in the program, and to control the number of concurrency of threads to avoid thread blocking caused by preempting resources each other.
Other optimization
1. Use less enumerations, which take up a lot of space.
2. Use Android-specific data structures, such as SparseArray, instead of hashMap.
3. Use soft references and weak references appropriately.
Encryption algorithms (base64, MD5, symmetric and asymmetric encryption) and usage scenarios.
What is Rsa encryption?
RSA algorithm is the most popular public key cryptography algorithm, which uses keys whose length can be changed. RSA is the first algorithm that can be used for both data encryption and digital signature.
The principle of RSA algorithm is as follows:
1. Randomly select two large prime numbers, p and Q, which are not equal to Q, and calculate N=pq.
two。 If you choose a natural number that is greater than 1 and less than N, the natural number e must be coprime with (pmae1) (qmer1).
3. The formula is used to calculate dvl d × e = 1 (mod (pmai 1) (Q mai 1)).
4. Destroy p and Q.
The final N and e are the "public key" and d is the "private key". The sender uses N to encrypt the data, and the receiver can only use d to unlock the data content.
The security of RSA depends on the decomposition of large numbers, and N less than 1024 bits has been proved to be insecure, and because the RSA algorithm is calculated in large numbers, the fastest situation of RSA is also times slower than that of DES, which is the biggest defect of RSA, so it can only be used to encrypt a small amount of data or encryption keys, but RSA is still a high-strength algorithm.
Usage scenario: in addition to login, payment and other interfaces using rsa asymmetric encryption, the project uses aes symmetric encryption. Today, let's take a look at aes encryption.
What is MD5 encryption?
MD5 English full name "Message-Digest Algorithm 5", translated is "message digest algorithm 5", evolved from MD2, MD3, MD4, is an one-way encryption algorithm, is an irreversible encryption method.
What are the characteristics of MD5 encryption?
Compressibility: any length of data, the calculated MD5 value length is fixed.
Easy to calculate: it is easy to calculate the MD5 value from the original data.
Anti-modification: any change to the original data, even if only modify 1 byte, the MD5 value obtained is very different.
Strong anti-collision: knowing the original data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, forged data).
MD5 application scenarios:
Consistency verification
Digital signature
Secure access authentication
What is aes encryption?
Advanced encryption Standard (Advanced Encryption Standard, abbreviation: AES), also known as Rijndael encryption method in cryptography, is a block encryption standard adopted by the federal government of the United States. This standard, which is used to replace the original DES, has been analyzed by many parties and is widely used all over the world.
This is the end of the content of "what are the Advanced Android interview questions"? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.