If you are reading my article for the first time, you can follow me, update all kinds of technical articles every day, and share more hot things in the programmer circle.
preface
Every programmer wants to enter big factory, seek better development. Nowadays, programmer job-hopping has become a common phenomenon, but the interview of large factories is like a mountain blocking the steps of most programmers, in addition to their own project experience, the most important thing is that some basic knowledge is not reliable. Some programmers go into an interview and discover that their tech stack is out of sync with what they’re looking for. What’s more, even answering questions about basic knowledge faltered.
In a large factory interview may also have the following problems:
- Lack of practical experience, will not live to learn and use
- Too little understanding of the process of technology landing in a project
- The underlying knowledge of technology is weak
Input is an important skill for a programmer, and you can grow by doing programming, reading books, or communicating with people in your industry.
Here are some advanced Android interview questions to help you turn the tide.
In the process of interviewing big factory, it is exactly these seemingly basic problems, the most easy to open the gap with others, depending on your understanding of the principle is not deep
In this first wish everyone happy to increase salary Offer!
What is ANR and how can it be avoided?
A: On Android, if your Application is not responsive for a period of time, the system displays a dialog box to the user. This dialog box is called ANR (Application NotResponding) dialog box.
Users can choose to keep the program running, but they don’t want to have to deal with this dialog every time they use your application. So, it’s important to design responsiveness in your program so that the system doesn’t show the ANR to the user.
The ANR takes five seconds for an Activity, 10 seconds for a BroadCastReceiver, and 20 seconds for a Service (both foreground).
If you have problems with your development machine, you can check /data/anr/ testamp.txt for the latest ANR information at the beginning.
- The main thread is blocked by IO operations (network IO is not allowed in the main thread after 4.0).
- There are time-consuming calculations in the main thread
- Error operations in the main Thread, such as Thread.wait or thread. sleep, will be monitored by the Android system. Once the following two situations occur, the ANR dialog box will be displayed and the application does not respond to user input events (such as keystrokes or touches) within 5 seconds.
- The BroadcastReceiver does not complete processing within 10 seconds
- The Service could not process for 20 seconds at a certain time
Fixed:
- Use AsyncTask to process time-consuming I/O operations.
- Called when using Thread or HandlerThread
- Process. SetThreadPriority (Process. THREAD_PRIORITY_BACKGROUND) set priority, otherwise will still be lower
- The program responds because the default Thread has the same priority as the main Thread.
- Instead of blocking the main Thread with thread.wait () or thread.sleep (), use handlers to process worker Thread results.
- Try to avoid time-consuming code in the Activity’s onCreate and onResume callbacks.
- IntentService is recommended for onReceive code in BroadcastReceiver to minimize time consumption.
Solution:
Put all time-consuming operations such as network access, Socket communication, querying a large number of SQL statements, complex logic calculations, etc. into child threads, and then update the UI with handler.sendMessage, runonUIThread, AsyncTask, RxJava, etc. Make sure the user interface is smooth at all costs. If a time-consuming operation requires the user to wait, a degree bar can be displayed on the interface.
2. What are the Activity and Fragment life cycles?
3. The Activity lifecycle when switching between horizontal and vertical screens
Android :confifigChanges when the Activity is not set, the lifecycle is recalled, once for landscape and twice for portrait.
Android :confifigChanges= “Orientation” When setting the Activity’s Android :confifigChanges= “Orientation”, each life cycle will still be called when cutting the screen, and switching between horizontal and vertical screens will only be performed once
Set up the Activity of the android: confifigChanges = “orientation” | “keyboardHidden, cut the screen each life cycle will not call again, will only perform onConfifigurationChanged method
4. Defects and problems of AsyncTask, and explain its principle.
What is AsyncTask?
AsyncTask is a lightweight asynchronous task class that performs background tasks in a thread pool, then passes the progress and final results of the execution to the main thread and updates the UI in the main thread.
AsyncTask is an abstract generic class. It provides three generic parameters: Params, Progress, and Result. Params indicates the type of the parameter, Progress indicates the Progress and type of the background task, and Result indicates the type of the Result returned by the background task. If AsyncTask does not need to pass specific parameters, these three generic parameters can be replaced by Void.
About thread pools:
The AsyncTask thread pool, ThreadPoolExecutor, is shared within the process scope and is static, so AsyncTask controls all subclass instances within the process scope. Because of this limitation, when using the default thread pool, if the number of threads exceeds the maximum capacity of the thread pool, the thread pool will burst (after 3.0, the default is serial, no problem). In this case, you can try to customize the thread pool to work with Asynctask.
About the default thread pool:
In AsyncTask, the thread pool is a thread pool with CPU + 1 core thread, CPU * 2 + 1 maximum thread number, 128 work queue length, and 28 maximum wait queue number. However, you can customize the thread pool. Thread pools are handled by asyncTasks. Thread pools allow tasks to run in parallel. Note that data consistency is a problem in concurrent cases, where new data may be overwritten by old data. So if you want tasks to run serially, use SERIAL_EXECUTOR.
Differences between AsyncTask in different SDK versions:
The reason why the execute method of AsyncTask cannot execute the program immediately and the improvement scheme After checking the official documents, we found that when AsyncTask was first introduced, asynchronous tasks were executed sequentially in an independent thread, that is to say, only one task was executed at a time, not in parallel. Starting from 1.6, AsyncTask introduces a thread pool that allows up to five asynchronous tasks to be executed simultaneously. This means that only five threads are allowed to run, and the remaining threads must wait until one of the tasks is completed. In other words, if there are more than five AsyncTask instances in the process, the sixth one will have to wait if the first five are all running for a long time. This is a limitation of AsyncTask and is not fixed prior to 2.3. If your application requires a large number of background threads to perform tasks, you may have to abandon AsyncTask and create your own Thread pool to manage threads. I have to say that while AsyncTask is better
Threads are convenient to use, but they can only run up to five threads at a time, which limits their usefulness. You have to carefully design your application to staggered AsyncTask times, try to be as time-sharing as possible, or keep the number of asyncTasks to no more than five, otherwise you will encounter the problems mentioned above. Perhaps Google has realized the limitations of AsynTask and has made some changes to the AsyncTask API since Android 3.0: only one thread is started to perform one task at a time, and then the second task is executed, so that only one background thread is performing the submitted task.
AsyncTask principle
AsyncTask has two thread pools (SerialExecutor and THREAD_POOL_EXECUTOR) and one Handler (InternalHandler). The thread pool SerialExecutor is used to queue tasks. The thread pool THREAD_POOL_EXECUTOR is used to actually execute the task, and InternalHandler is used to switch the execution environment from the thread pool to the main thread.
SHandler is a static Handler object that must be created on the main thread in order to switch the execution environment to the main thread. Since static members are initialized when the class is loaded, the AsyncTask class must be loaded in the main thread, otherwise all asyncTasks in the same process will not work properly.
What is the priority of the process in Android?
1. Foreground process:
The foreground process is the last to be killed if the system is running out of memory
2. Visible processes:
It can be an onPause Activity or a Service bound to it that is visible to the user but cannot interact with the user because it is out of focus
3. Service process:
The Service started by startService is not visible to the user, but it is concerned by the user. For example, the user is listening to the music in the non-music interface or downloading the file on the non-download page. The first two processes are terminated when the system needs space to run
4. Background processes
Which is running the onStop method and stop the program, but it is not the user’s current concern, such as QQ hanging in the background, then the process system once there is no memory will be killed first
5. Empty process:
A process that does not contain any application, such a process system is generally not allowed to exist
Why should the Bunder pass object be serialized? The difference between Serialzable and Parcelable?
Because the Bundle only supports basic data types when passing data, it needs to serialize to a stored or transportable intrinsic state (byte stream) when passing objects. Serialized objects can be transferred between the network, IPC (such as an Activity that starts another process, Service, and Reciver), or stored locally.
Serializable (Java built-in) :
Serializable stands for serialization, which means converting an object to a stored or transportable state. Serialized objects can be transferred over the network or stored locally.
Parcelable (Android only) :
In addition to Serializable, the same effect can be achieved with Parcelable. Instead of serializing an object, Parcelable splits the entire object into the data type supported by the Intent. This implements the function of passing objects.
The differences are summarized as follows:
Seven, animation,
- Tween animation. By specifying the View at the beginning and end of the state and change mode, the content of the View to complete a series of graphic transformation to achieve animation effect. Alpha, Scale,Translate, Rotate.
- Frame Frame animation. AnimationDrawable controls the animation-list.xml layout
- Introduced in PropertyAnimation 3.0, the core idea of PropertyAnimation is the change of value.
Property Animation has two steps:
1. Calculate the attribute value
2. Set the property values for the properties of the target object, that is, apply and refresh the animation
The calculation of attributes is divided into three processes:
A process:
Calculate elapsed fraction. To perform an animation, you need to create a ValueAnimator and specify the start, end, and duration of the target object properties. During the entire animation process after the start call, ValueAnimator calculates a score between 0 and 1, representing the percentage of completed animations for the animation, based on the animation time that has been completed. 0 means 0% and 1 means 100%.
Process 2:
Interpolated fraction computing interpolation (animation change rate) interpolated fraction. After ValueAnimator has interpolated an animation score, it will invoke the current interpolator to interpolate a score. During interpolating, the percentage of the animation that has been interpolated will be added to the new interpolation calculation.
Third process:
Evaluating attribute Values When the interpolation score is calculated, ValueAnimator calls the appropriate TypeEvaluator based on the interpolation score to evaluate the attribute values in the motion.
The above analysis introduces two concepts: Elapsed fraction and interpolated fraction.
Principle and characteristics:
1. Property animation:
Interpolator: The function is to calculate the percentage of the property change based on the percentage of time elapsed.
Estimator: on the basis of 1 by this thing to calculate how much the value of the property change class is actually the use of interpolator and estimator, to calculate the View at each moment of the property, and then change the View properties to achieve the View animation effect.
2. View the animation:
It’s just that the image has changed, and the view’s actual location is still where it was.
3. Frame animation:
AnimatonDrawable is an animation that is played using an AnimatonDrawable after a series of images are defined in XML. Their differences:
- Property animation is the real implementation of view movement, tween animation to view movement is more like drawing a shadow in a different place, the actual object is still in the original place.
- When the repeatCount of the animation is set to infinite, if the animation is not stopped when the Activity exits, the property animation will cause the Activity to be unable to be released, resulting in a memory leak, whereas the tween animation is fine.
- XML file tween animation, reuse rate is very high. In the Activity switch, window popup and other scenarios have a good effect.
- When using frame animation, be careful not to run out of memory by using too many extremely large images.
Why is property animation still clickable after moving?
When we play the tween animation, the changes we see are only temporary. Property animation, on the other hand, what it changes is updated to the matrix corresponding to the View, so when the ViewGroup dispatches the event, it correctly converts the current touch coordinates to the matrix changed coordinates, which is why playing the tween animation doesn’t change the touch area.
How to compress the size of Apk?
Reference Answer:
A full APK contains the following directories (drag the APK files to Android Studio) :
- Meta-inf / : contains cert. SF and cert. RSA signature files and manifest.mf MANIFEST files
- Assets / : contains the application resources that the application can search for using the AssetManager object.
- Res / : contains the uncompiled resource resources.arsc.
- Lib / : contains compiled code specific to the processor software layer. The catalog contains subdirectories for each platform, such as Armeabi, Armeabi-V7A, ARM64-V8A, x86, X86_64, and MIPS.
- Resources.arsc: contains compiled resources. This file contains the XML content in all configurations of the RES /values/ folder. The packaging tool extracts this XML content, compiles it into binary format, and archives the content. This content includes language strings and styles, as well as content paths, such as layout files and images, that are directly contained in **resources.arsc*8 files.
- Classes.dex: contains classes compiled in a dex file format that the Dalvik/ART virtual machine understands.
- Androidmanifest.xml: Contains the core Android manifest. This file lists the application name, version, access rights, and referenced library files. This file uses Android’s binary XML format.
- Lib, class.dex, and RES take up more than 90% of the space, so these three blocks are the key to optimizing Apk size.
Reduce res and compress graphic files
Image file compression is for JPG and PNG images. We usually place multiple sets of images with different resolutions to fit different screens, and we can cut them down appropriately here. In practice, it is enough to keep one or two sets (keep xxHDPI for one set, add HDPI for two sets) and then compress the rest of the images (use superior compression for JPG, try pngquant compression for PNG)
Reduce the dex file size
- Add Resource Confusion
- ShrinkResources is true to remove unreferenced resources, which works in conjunction with code compression.
- If minifyEnabled is true, code compression is enabled through ProGuard, obfuscating code and removing unused code in conjunction with the configuration of proguardFiles.
- Code obfuscation improves security while compressing APK.
Reduce the lib file size
- Because many third-party libraries are referenced, the lib folder can often take up a lot of space, especially if the so library is available. Many so libraries introduce armeabi, Armeabi-v7A, and x86 at the same time. You can just keep one of armeabi or Armeabi-V7A here. In fact, wechat and other mainstream apps do this.
- Gradle can be configured directly. NDK can be configured as well
Due to the large content, the article space is limited, the article ends here. The so-called easy to know difficult to do, the end of the article, it is the beginning of action, wish you use action, to create a piece of flowers like a brocade.