I was asked about the database in an interview. Network request.intentService.view drawing. Memory leak. OOM. Animation frame. Custom view.Glide source code. Property animation and so on a series of questions, although all answered up, but there are still some details that are not noticed.

After coming back, I organized a lot of knowledge into a PDF, which is relatively comprehensive (▽)

BATJ. Bytedance Interview Topics, Algorithms topics, High-end Technology Topics, Mixed Development Topics,Java Interview Topics, Android,Java tips, to Performance Optimization. Threads. View.opencv.ndk. There are supplementary related video + study notes


Download more complete project. To be continued. The source code. Github. You can click about me to contact me for the full PDF github.com/xiangjiana/…

1. What are the operation types of databases and how do I import external databases?

Read the questions. Ask the interviewer if the question is vague.

Cooperate with the interviewer to interview: the interview is a mutual understanding process, to make full use of the interview questions and time to show their abilities and skills, the interviewer can see your real skills.

1) What are the ways to use the database?
  • openOrCreateDatabase(String path);
  • inheritanceSqliteOpenHelperClass to manage databases and their versions (onCreate.onUpgrade)

    When a method of this class is called in a programgetWritableDatabase()orgetReadableDatabase();“Will open the database. If no database file is available, the system automatically generates a database.
2) Operation type: add, delete, modify and check CRUD

ExecSQL (SQL); execSQL(SQL); Insert (table, nullColumnHack, ContentValues);

How do I import an external database?

External database files may be stored in the SD card or res/raw or assets directory.

OpenOrCreateDatabase (db.openOrCreateDatabase); /database/openOrCreateDatabase(db); /database/openOrCreateDatabase(db); This is what I did in my last project. Before the app was launched, some initial data needed to be built in, and there would also be problems such as data upgrade, so I did this… At the same time, I encountered the most interesting problem is about the database concurrent operation problem, such as: multi-thread operation database, I adopted the use of mutex encapsulation to solve……

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

The local broadcast mechanism was introduced to address security issues:

1) The broadcast being sent will not be separated from the application, so as to worry about data leakage of the APP; 2) Other programs cannot be sent to my application, so I don’t worry about security vulnerabilities. (For example: how to make an unkillable service – listening to popular apps such as wechat, Umeng, aurora broadcast, to boot themselves.) 3) Sending local broadcasts is more efficient than sending global broadcasts. Global broadcast The broadcast collection table to maintain is less efficient. Global broadcasting, meaning it can cross processes, requires low-level support.

Local broadcasts cannot be registered statically. —- static registration: can do program stop can also listen. Use:

  • Registration:

    LocalBroadcastManager.getInstance(this).registerReceiver(new XXXBroadCastReceiver().new IntentFilter(action));
  • Cancel registration:

    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)

3. Have you used IntentService? What is it for?

If you have a task that can be broken up into subtasks that need to be done in order, IntentService is the best choice if you need to put it into a service.

Typically, a Service runs on the main thread, so writing time-consuming operation code inside a Service will trap the main thread into ANR. To solve such problems, Google introduced IntentService.

IntentService has the following advantages: (1) It creates a separate worker thread to handle all intents. (3) There is no need to actively call stopSelf() to terminate the service, because the source code implements automatic shutdown. (4) Null returned by onBind() is implemented by default. (5) The default implementation of onStartCommand() aims to insert the intent into the work queue.

Summary: What are the benefits of using IntentService? First, it saves the trouble of manually opening the thread; Second, do not stop the service manually; Third, because of the work queue design, startService() can be started multiple times, but there is only one service instance and one worker thread. One by one familiar with anger execution.

What problem does AIDL solve? AIDL stands for Android Interface Definition Language. Since memory cannot be shared between processes in the Android system, you need to provide some mechanism for data communication between different processes.

Remote Procedure Call: RPC – Remote Procedure Call. Android provides an IDL solution to expose its service interface. AIDL: Can be understood as an agreement between two parties. Both parties must hold the text protocol XXX. Aidl file (android internal compilation will translate aiDL into a XXX. Java file – proxy mode: Binder driver, Linux communication). There is a lot of use of AIDL in system source code, such as system services. TV set top box system development. Your service should be exposed to other developers.

Explain the Binder mechanism.

4. What is the difference between Activity, Window and View?

How activities, Windows, and Views work together to display the interface. — Test point: display process (view drawing process) source familiarity.

Activity a person who cuts window cuts Window (a model of bearing); View window (View to display); LayoutInflater scissors – Cut layouts into paper-cuts. (Alt+ direction arrow)

Fragment characteristics? (Have you had fun using fragments, or stepped in holes?)

Fragment design is mainly to break the Activity interface, including its logic, into many independent modules, so that module reuse and more flexible assembly to present a variety of interfaces.

  • Fragments can be formed as part of the Activity interface;
  • You can have multiple fragments in an Activity, and a Fragment can be used in multiple activities.
  • You can dynamically add, remove, and replace fragments while an Activity is running.
  • Fragments have their own life cycle and can respond to input events.

Potholes:

  • Overlapping;
  • annotationsnewAPI(Compatible package);
  • Setarguement()Initialize data;
  • Not in theonsave. () method, commit;
  • On and off the stack problem; – the transaction. Act like an Activity jump, and return to the previous page with the state still there. Replace (F1, F2) seriously affects the lifecycle :add()+show+hide

5. The lower version SDK implements the higher version API

Several cases:

1) In general, many new apis of higher versions will find alternative implementations in compatibility packages. Such as fragments. Notification, which has the NotificationCompat class in the V4 compatibility package. 5.0+ backgroundTint, minSdk < 5.0 will detect errors, V4 compatible package DrawableCompat class. 2) Manual implementation without alternative implementation. For example: control water ripple effect – third party implementation. Or simply remove the effect in the lower version. 3) Supplement: If minSDK is set but a higher version of API is used in the code, there will be a detection error. You need to use declarative compile detection policies in your code, such as @suppressLint and @targetAPI annotations to inform the compiler of compiled rules. @SuppressLint is ignored detection; @targetAPI =23, which will match the SDK version exactly according to the API used in your function. 4) To avoid positional errors, it is best not to use deprecated apis. (There are no compatibility issues in general, and this API method may be removed at any time later; Performance issues.)

6. Launch Mode

Stack: Advanced after standard mode SingleTop: use scenario: browser bookmarks; Communication message chat interface. SingleTask: Usage scenario: when an Activity is used as the main screen. SingleInstance: Usage scenario: For example, BrowserActivity is a memory intensive Activity that many apps will call, so you can set the Activity to SingleInstance mode. For example: alarm clock alarm clock.

7. View drawing process

-Leonard: You Measure yourself. If it is a ViewGroup, you need to measure all childViews in it. What about the results of the measurements? setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState); Set your own size. -Leonard: I don’t know where you’re laying yourself out. If it is a ViewGroup, we need to issue all childViews in it. How to put it specifically? The 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)
         */
Copy the code

8. What causes a memory leak

1) What is a memory leak: it is best to explain the GC garbage collection mechanism and the concept of GC Root. 2) Why there are memory leaks: Because memory leaks are caused by human error. And the object oriented development relationship is complex, multi-threaded relationship, it is easy to appear reference hierarchy is very deep and very chaotic. 4) How to solve memory leaks

9. ANR positioning and correction

You can view anR information by viewing /data/anr/ testamp. TXT. The root cause is that the main thread is blocked, causing the application to fail to respond to user input events for 5 seconds.

There are many different scenarios for ANR errors:

  • IO/ network operations are performed on the main thread, which is prone to block.
  • A time-consuming calculation was performed in the main thread. —- this is often done in the onDraw method when customizing controls.

    (Also talk about custom control performance optimization: inonDrawCreating objects in it is easy to cause memory jitter – draw actions are called a lot and generate a lot of garbage objects which causes memory jitter when GC is very frequent. Memory jitter is easy to cause the UI to drop frame lag
  • BroadCastReceiverProcessing is not completed within 10 seconds.
  • BroadCastReceivertheonReceivedIt is recommended to minimize time-consuming operations in codeIntentServiceTo deal with.
  • The Service performs the time-consuming operation. Since the Service is also executed in the main thread, the time-consuming operation should be done by opening a child thread inside the Service.
  • useAsyncTaskProcess time-consuming I/O operations.
  • Use Thread orHandlerThreadWhen usingProcess.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)orJava. Lang. Thread. SetPriority (int priority)Set the priority to background priority, so that other multithreading concurrent CPU consumption is reduced, in favor of the main thread processing.
  • The Activity ofonCreateandonResumeThe most time-consuming operation in a callback.

10. What causes oom

OOM causes: The memory is insufficient. The Android system sets a hard condition for each application: DalvikHeapSize The maximum threshold is 64M, 48M, or 24M. If your application is near this threshold, you will receive OOM if you try to allocate memory again.

  • A lot of memory leaks will easily lead to OOM
  • Big picture processing. Compress the image. Development should pay attention to frequent object creation and collection.
  • Can be appropriately tested:ActivityManager.getMemoryClass()Can be used to query the current applicationHeapSizeThresholds. You can name itadb shellgetProp | grep dalvik.vm.heapxxxlimitLook at it.

How to avoid memory leaks: 1) Reduce the memory footprint of objects:

  • Use more lightweight data structures:

    Consider alternatives where appropriateHashMapAnd other traditional data structures, using Android data structures developed specifically for mobile phonesArrayMap/SparseArray. SparseLongMap/SparseIntMap/SparseBoolMapMore efficient.

    HashMap.put(string,Object); Object o = map.get(string);This can lead to unnecessary automatic packing and unpacking.
  • Avoid using enums in Android properly and use static constants instead. (More enumerations are generally preferred – architectural aspects of software; You should be more inclined to solve performance problems if you encounter heavy use of this enumeration. .
  • Less memory footprint for Bitmap objects.

    useinSampleSize:Image compression can avoid large image loading by calculating the image compression ratioOOM;

    decodeformat: Image decoding format selection,ARGB_8888/RGB_565/ARGB_4444/ALPHA_8, can also be usedWebP.
  • Use smaller image resources. Is there any space in the image that can be further compressed?

2) Reuse of memory objects: using object pool technology, two kinds:

Write their own; Leverage the system’s existing object pooling mechanism. For example, LRU(Last Recently Use) algorithm.

  • a.ListView/GridViewYou can see reuse in the source codeConvertViewReuse.RecyclerViewIn theRecyclerThe source code.
  • B.B itmap reuse

    ListviewTo display a large number of images. You need to useLRUCaching mechanism to reuse images.
  • c.To avoid theonDrawMethod to perform object creation, to reuse. Avoid memory jitter.
  • **d ** Common Java infrastructure issues —StringBuilderEtc.

4) Use some memory optimization strategies: read the documentation

11. Several ways to communicate between Android Services and activities

1) through Binder 2) through broadcast

12. API differences between Android versions

Keep a few key release features in mind: 3.0/4.0, 4.4, 5.0, 6.0/7.0

13.Requestlayout, OnLayout, onDraw, DrawChild

RequestLayout() method: This causes the Measure() method and Layout() to be called. Will determine if onDraw() is needed based on flag bits; OnLayout () : places child controls in viewGroup onDraw() : draws the view itself; DrawChild (): calls back the draw method of each child view. child.draw(canvas, this, drawingTime);

14. Invalidate() and postInvalidate(

Invalidate () : refresh in the main thread; PostInvalidate () : refresh in child threads; Instead, invalidate is called, again using the mechanism by which the worker thread sends a message to the main thread.

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;Copy the code

15. Implementation principle of Android animation framework

Traditional animation framework: view.startAnimation (); Disadvantages: Can’t click after moving. The reason? It has to do with the implementation mechanism. All of the transparency, rotation, pan, zoom animations are done with the view constantly refreshing and calling Draw. Call canvas. Translate (XXX), canvas. ScaleX (XXX)… .xxx :matrix pixel matrix to control the data of animation. Remember to look at the source code, combined with multiple scaled demo to see the source code.

16. How much memory does Android allocate for each application?

Look at the specific mobile phone platform, the common ones are: 64M/32M, etc

17. LinearLayout contrast RelativeLayout

Performance comparison: LinearLayout performs better than RelativeLayout. Because RelativeLayout measures twice. By default (no weight is set) the LinearLayout will only be measured once.

Why does RelativeLayout measure twice? The arrangement of the subviews within a RelativeLayout is based on dependencies that may not be related to the order of the views in the layout. When determining the position of each subview, you must first order each subview. And because a RelativeLayout allows for horizontal and vertical interdependence, you need to do a sorting measure for horizontal and vertical.

18. Optimize custom Views

1) Reduce heavy computations and object creation and heavy memory allocation in onDraw. 2) Invalidate () should be used as little as possible. 3) View time-consuming operation layout. Reduce requestLayout () to prevent the UI system from revisiting the entire tree. Mearsure. 4) If you have a complex layout, it is better to implement the complex layout directly using your own written ViewGroup. Reduce the hierarchical relationship of a tree is all their own measurement and layout, to achieve the purpose of optimization. (Facebook does this a lot.)

19.ContentProvider

Tip: Cross-process communication. Data is shared between processes. ; Source code to a chop.

Fragment life cycle

21. The volley

22. Android Glide source code analysis

23. Android properties animation features

24. How to ensure that a background service is not killed, and what is the way to save power?

25. Touch event delivery process

26. Differences between Handler, Thread and HandlerThread

Describe the flow of a network request

Please see the full PDF version (more complete project downloads). To be continued. The source code. Github. You can click about me to contact me for the full PDF github.com/xiangjiana/…