Android basics and underlying mechanism interview questions

1. What are the types of database operations and how to import external databases?

Understand the topic. If you encounter a vague question, you can ask the interviewer appropriately.
Cooperate with the interviewer for the interview: Interview is a process of mutual understanding. You must make full use of the interview questions and time to show your abilities and skills, so that the interviewer can see your true skills.

1) What are the ways to use the database?

(1) openOrCreateDatabase(String path);
(2) Inherit the SqliteOpenHelper class to manage the database and its version (onCreate, onUpgrade) When the method getWritableDatabase() or getReadableDatabase(); of this class is called in the program, the database will be opened . If there is no database file at that time, the system will automatically generate a database.

2) Operation type:
add, delete, modify, check CRUD, directly manipulate SQL statements: SQliteDatabase.execSQL(sql); Object-oriented operation: SQLiteDatabase.insert(table, nullColumnHack, ContentValues);

How to import an external database?

Generally, external database files may be placed under the SD card or res/raw or assets directory. Write a DBManager class to manage, move the database file, first copy the database file to the "/data/data/package name/databases/" directory, and then open the database for use through db.openOrCreateDatabase (db file). This is what I did in my last project. Because there are some initial data that needs to be built-in before the app is launched, I will also encounter problems such as data upgrades. I did this... At the same time, the most interesting problem I encountered was about database concurrency. Operational problems, such as: when multi-threaded operation of the database, I use encapsulation and use mutex locks to solve...

2. Have you ever used local broadcast? What is the difference between it and global broadcast?

The mechanism of introducing local broadcast is to solve the security problem:
1) The broadcast that is being sent will not be separated from the application, and it is better to worry about the data leakage of the app;
2) Other programs cannot be sent to my application, so I don’t worry about security. Loopholes. (For example: How to make a service that cannot be killed-listen to fire apps such as WeChat, Youmeng, and Jiguang broadcasts to start yourself.)
3) Sending local broadcasts is more efficient than sending global broadcasts. (The broadcast set table to be maintained by the global broadcast is less efficient. The global broadcast means that it can be cross-processed and requires the support of the bottom layer.)

Local broadcast cannot use static registration. ----Static registration: It can monitor after the program stops. Use:
(1) Register :
LocalBroadcastManager.getInstance(this).registerReceiver(new XXXBroadCastReceiver(), new IntentFilter(action));
(2) Unregister :
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiv er)

3. Have you ever used IntentService, what is its function, and what problem does AIDL solve? (Xiaomi)

If there is a task, it can be divided into many subtasks, which need to be completed in order. If it needs to be completed in a service, then using IntentService is the best choice.
Generally, the Service we use runs in the main thread, so if we write time-consuming operation code in the service, the main thread will get ANR. In order to solve such problems, Google introduced IntentService. The advantages of IntentService:
(1) It creates an independent worker thread to handle all an intent.
(2) Create a work queue to send intents to onHandleIntent() one by one.
(3) There is no need to call stopSelf() to end the service, because the source code implements automatic shutdown by itself.
(4) The null returned by onBind() is implemented by default.
(5) The purpose of the default implementation of onStartCommand() is to insert the intent into the work queue.

Summary : What are the benefits of using IntentService. First, it saves the trouble of manually starting threads; second, there is no need to manually stop the service; third, because the work queue is designed, it can be started multiple times—startService(), but there is only one service instance and one worker thread. Be familiar with the execution one by one.

What problem does AIDL solve?

The full name of AIDL: Android Interface Definition Language, Android Interface Definition Language. Since memory cannot be shared between processes in the Android system, some mechanisms need to be provided for data communication between different processes.
Remote procedure call: RPC—Remote Procedure Call. Android provides an IDL solution to expose its service interface. AIDL: It can be understood as an agreement between the two parties. Both parties must hold this agreement-the text agreement xxx.aidl file (when Android is compiled internally, the aidl protocol will be translated into a xxx.java file-proxy mode: Binder driver related, Linux underlying communication related.)

There are a lot of aidl used in the system source code, such as system services.

TV set-top box system development. Your service should be exposed to other developers to use. Explain the Binder mechanism

4. What are the differences between Activity, Window and View, and what are the characteristics of fragment? (360)

How do the three of Activity, Window, and View display the interface together. —Test point: Familiarity with the source code of the displayed process (view drawing process).
Activity cuts the window grille (controlling); Window window (a model carried); View window grille (the view to be displayed); LayoutInflater scissors-cut the layout (drawing) into window grilles. (Alt+direction arrow)

What are the characteristics of fragment? (Have you experienced some fun with fragments, or have you stepped on any pits?)
The design of fragments is mainly to break the Activity interface including its logic into many independent modules, which facilitates the reuse of modules and more flexible assembly Present a variety of interfaces.

1) Fragment can be used as a part of the Activity interface;
2) Multiple Fragments can appear in one Activity, and one fragment can be used in multiple Activities;
3) During Activity running, it can be dynamically added, deleted, and replaced Fragment.
4) Fragment has its own life cycle and can respond to input events.

Pit stepped on:

  1. overlapping;
  2. Annotate newAPI (compatibility package solution);
  3. Setarguement() initialize data;
  4. Cannot commit; after the onsave...() method
  5. Stack-to-stack problem;-Transaction.

It has the same effect as Activity jump, and when you return, you can return to the previous page (fragment) and the state is still there. replace(f1, f2) seriously affects the life cycle: add()+show+hide

5. Low version SDK implements high version api (Xiaomi)

Two situations:
1) Generally, many new APIs of higher versions will find alternative implementations in the compatibility package. Such as fragment. Notification, there is a NotificationCompat class in the v4 compatibility package. 5.0+ If the backgroundTint and minSdk are less than 5.0, the detection error will be included. The v4 compatibility package DrawableCompat class.
2) Manual implementation without alternative implementation. For example: the water ripple effect of the control-a third-party implementation. Or remove this effect directly in the lower version.
3) Supplement: If minSDK is set but a higher version of API is used in the code, a detection error will occur. You need to use declarative compilation detection strategies in the code, such as: @SuppressLint and @TargetApi annotations to prompt the compiler to compile rules. @SuppressLint ignores detection; @TargetApi=23, will strictly match the SDK version according to the API used in your function, and give the corresponding compilation error prompt.
4) In order to avoid location errors, it is best not to use obsolete APIs. (Under normal circumstances, there will be no compatibility issues. This API method may be deleted at any time later; performance issues.)

6. Launch mode application scenarios (Baidu, Xiaomi, LeTV)

Stack: first-in, last-out
Standard mode
SingleTop: usage scenarios: browser bookmarks; communication message chat interface.
SingleTask: Usage scenario: when an Activity is used as the main interface.
SingleInstance: Usage scenario: For example, the BrowserActivity is very memory intensive, and many apps will need to call it, so that the Activity can be set to singleton mode. For example: alarm clock.

7. View drawing process (Baidu)

Measure: measure, measure yourself. If it is a ViewGroup, it needs to measure all the childviews in it.
What should I do? setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState); Set your own size.
Layout: Place, where to put yourself. If it is a ViewGroup, it needs to distribute all the childviews in it.
How to put it specifically?

Draw: draw

/*
 * Draw traversal performs several drawing steps which must be executed
 * in the appropriate order:
 *
 * 1. Draw the background 
 * 2. If necessary, save the canvas' layers to prepare for fading
 * 3. Draw view's content
 * 4. Draw children
 * 5. If necessary, draw the fading edges and restore layers
 * 6. Draw decorations (scrollbars for instance) */

8. What causes a memory leak (Meituan)

1) What is a memory leak: It is best to explain the GC garbage collection mechanism and the concept of GC Root.
2) Why is there a memory leak: Because the memory leak is caused by human error. Moreover, object-oriented development has complex and multi-threaded relationships, and it is prone to deep and chaotic references to hierarchical relationships.
3) What situations are likely to cause memory leaks;
4) How to solve memory leaks;

9. ANR positioning and correction

You can view the ANR information by viewing /data/anr/traces.txt.
The root cause is: the main thread is stuck, causing the application to fail to respond to user input events within 5 seconds.
There are many scenarios where ANR errors occur:
1) IO/network operations are executed in the main thread, which is easy to block.
2) Time-consuming calculations are performed in the main thread. ----It is often done in the onDraw method when customizing the control. (At the same time, let’s talk about the performance optimization of custom controls: creating objects in onDraw can easily lead to memory jitter—drawing actions will be called continuously, and a large number of garbage objects will be generated, resulting in frequent GC and memory jitter.) Memory jitter is likely to cause UI There is a problem of frame dropping and freezing.
3) BroadCastReceiver did not complete the processing within 10 seconds.
4) The onReceived code of BroadCastReceiver should also minimize time-consuming operations. It is recommended to use IntentService for processing.
5) Service performed a time-consuming operation, because the service is also executed in the main thread, so the time-consuming operation should be opened in the service in the child thread to do.
6) Use AsyncTask to handle time-consuming IO and other operations.
7) When using Thread or HandlerThread, use Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND) or java.lang.Thread.setPriority (int priority) to set the priority to the background priority, so that other multi-threaded concurrent consumption of CPU time will be reduced Reduced, which is conducive to the processing of the main thread.
8) As much time-consuming operations as possible in Activity's onCreate and onResume callbacks.

10. What causes oom (LeEco, Meituan)

The reason for OOM: insufficient memory, the android system sets a hard condition for each application: DalvikHeapSize maximum threshold 64M/48M/24M. If your application memory usage is close to this threshold, if you try again at this time OOM will be caused when memory is allocated.
1) More memory leaks can easily lead to OOM
2) Processing of large images. Compress picture. Usually development should pay attention to the frequent creation and recycling of objects.
3) Appropriate detection: ActivityManager.getMemoryClass() can be used to query the HeapSize threshold of the current application. It can be viewed by naming adb shellgetProp | grep dalvik.vm.heapxxxlimit.
How to avoid memory leaks:
1) Reduce the memory footprint of the object:
a) Use a more lightweight data structure: If appropriate, replace traditional data structures such as HashMap and use Android's data structure class ArrayMap/SparseArray specially developed for mobile phones. . SparseLongMap/SparseIntMap/SparseBoolMap is more efficient. HashMap.put(string,Object);Object o = map.get(string); will cause some unnecessary automatic boxing and unboxing.
b) Appropriately avoid using Enum enumeration in android, instead of using ordinary static constants. (Generally, we still advocate multi-use enumeration-software architecture design; if you encounter this enumeration that needs a lot of use, you should be more inclined to solve performance problems.).
c) Less memory usage of Bitmap objects. Use inSampleSize: to calculate the image compression ratio for image compression, which can avoid OOM caused by large image loading; decodeformat: the image decoding format selection, ARGB_8888/RGB_565/ARGB_4444/ALPHA_8, WebP can also be used.
d) Use smaller picture resources, whether there is space in the picture that can still be compressed.
2) Reuse of memory objects: Using object pool technology, two types:
1. Write
by yourself; 2. Use the existing object pool mechanism of the system. For example, LRU (Last Recently Use) algorithm.
a) ListView/GridView source code can see the reuse of ConvertView. Recycler source code in RecyclerView.
b) Bitmap multiplexing Listview etc. need to display a large number of pictures. Need to use LRU caching mechanism to reuse pictures.
c) Avoid creating objects in the onDraw method, and reuse them. Avoid memory jitter.
d) Common basic java problems—StringBuilder, etc.
3) Avoid object memory leaks;
4) Use some memory optimization strategies: see documentation

11. Several ways of communication between Android Service and Activity

1) Via Binder
2) Via broadcast

12. The difference between Android versions of API

Remember the features of several key versions: 3.0/4.0, 4.4, 5.0, 6.0/7.0...

13. The difference and connection between Requestlayout, onlayout, onDraw, DrawChild (Cheetah)

RequestLayout() method: will cause the Measure() method and layout() to be called. It will judge whether onDraw() is needed according to the flag bit;
onLayout(): place the child controls in the viewGroup
onDraw(): draw the view itself; (ViewGroup also needs to draw all child controls in it)
drawChild(): call back each one again The draw method of the subview. child.draw(canvas, this, drawingTime);

14. The difference and use of invalidate() and postInvalidate() (Baidu)

 invalidate():在主线程当中刷新;
 postInvalidate():在子线程当中刷新;其实最终调用的就是 invalidate,原理依然 是通过工作线程向主线程发送消息这一机制。 
 public void postInvalidate() {
    
    
    postInvalidateDelayed(0);
 }
 public void postInvalidateDelayed(long delayMilliseconds) {
    
    
     // We try only with the AttachInfo because there's no point in invalidating
     // if we are not attached to our window
   final AttachInfo attachInfo = mAttachInfo;
   if (attachInfo != null) {
    
     
      attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
   }
 }
    public void dispatchInvalidateDelayed(View view, long delayMilliseconds) {
    
    
       Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view); 
       mHandler.sendMessageDelayed(msg, delayMilliseconds);
       }
 public void handleMessage(Message msg) {
    
    
     switch (msg.what) {
    
    
     case MSG_INVALIDATE: ((View) msg.obj).invalidate();
    } 
          break;

15. Implementation Principle of Android Animation Framework (Tencent)

Traditional animation framework: View.startAnimation();
Disadvantage: Cannot click after moving. the reason? It has to do with the implementation mechanism.
All transparency, rotation, translation, and zooming animations are implemented when the view is constantly refreshed and called draw.
Call canvas.translate(xxx), canvas.scaleX(xxx)…. Xxx: matrix pixel matrix to control the animation data. Remember to look at the source code, and look at the source code with multiple zoomed demos.

16. What is the memory size allocated by Android for each application? (Meituan)

Depending on the specific mobile phone platform, the common ones are: 64M/32M, etc.

17. LinearLayout vs. RelativeLayout (Baidu)

Performance comparison: The performance of LinearLayout is better than that of RelativeLayout.
Because RelativeLayout will measure twice. By default (weight is not set) LinearLayout will only be measured once.
Why does RelativeLayout measure twice? First of all, the arrangement of subviews in RelativeLayout is based on the relationship of mutual dependence, and this dependence may have nothing to do with the order of views in the layout. When determining the position of each subview, you need to sort each subview first. And because RelativeLayout allows horizontal and vertical interdependence, it is necessary to perform a sorting measurement in both horizontal and vertical directions.

18. Optimize custom view (Baidu, LeTV, Xiaomi)

1) Reduce a large number of calculations and object creation and a large amount of memory allocation in onDraw.
2) The number of invalidate() should be used as little as possible.
3) Time-consuming operation layout in view. Reduce requestLayout() to avoid letting the UI system re-traverse the entire tree. Mearsure.
4) If you have a very complicated layout, it is better to use your own ViewGroup to implement this complicated layout. All the hierarchical relationships of the reduced tree are measured and laid out by themselves to achieve the purpose of optimization. (Facebook often does this)

19. ContentProvider (LeEco)

Tip: Cross-process communication. Data exchange and sharing between processes.

20. Fragment life cycle

21. Volley analysis (Meituan, LeTV)

22. Android Glide source code analysis

23. Android attribute animation characteristics (LeTV, Xiaomi)

to sum up

Everyone knows that the interview knowledge points like Android basics and underlying mechanisms are far more than this. I wanted to write more and share it for everyone to learn, but because the length of the article is limited, I can only share it here for the time being. . But I like to collect and sort out some Android-related interview questions in my spare time, and conduct my own brushing to test whether I meet the needs of the market position. If you want to learn about Android-related interview questions and some knowledge points, you can go directly to my GitHub Project address: https://github.com/733gh/Android-T3 for viewing.

Guess you like

Origin blog.csdn.net/u012165769/article/details/113871946