2020 Android interview key and difficult points (10000 words), dry goods and fine talk

JNI principle:

[analysis of registration process of Dalvik virtual machine JNI method]

Example: when libnanosleep When the so file is loaded, the function JNI_OnLoad will be called. In function JNI_ In onload, the parameter vm describes the Dalvik virtual machine in the current thread. A JNIEnv object can be obtained by calling its member function GetEnv. With this JNIEnv object, we can call another function jniRegisterNativeMethods to register a JNI method with the Dalvik virtual machine of the current process.

6.Android system startup process and App startup process

App startup process:

[detailed explanation of Activity startup process]

The process from desktop Click to activity launch

1. The Launcher thread captures the click event of onclick and calls Launcher Startactivitysafe, further call Launcher StartActivity, finally calling the startActivity of the parent class Activity.

2. The Activity interacts with the ActivityManagerService, introduces Instrumentation, gives the startup request to Instrumentation, and calls Instrumentation execStartActivity.

3. Call the startActivity method of ActivityManagerService, and process switching is done here (see the source code for the specific process).

4. Open the Activity and call the onCreate method

7.Activity,Fragment,Service life cycle

Common example: the program is running and a call is coming. What about this program? Abort. If a new Activity is full screen onPause - > onstop when aborting and OnStart - > onResume when resuming, if an Activity whose Theme is transparent or Dialog interrupts the application, it is only onPause and onResume when resuming.

  • onPause: onResume when resuming

  • onCreate: create an interface here to initialize some data

  • onStart: at this point, it becomes visible and non interactive

  • onPause: this step is visible but not interactive. The system will stop animations and other CPU consuming things. Some of your data should be saved here because the priority of your program is reduced and may be recycled by the system. The data saved here should be read out in onResume. Note: the time for doing things in this method should be short, because the next Activity will not start until this method is completed.

  • onStop: becomes invisible and is overwritten by the next Activity (is the difference between onPause and onStop visible)

  • onDestroy: This is the last method called before the Activity is killed. It may be that the external class calls the finish method or the system kills it temporarily to save space. You can use isFinishing() to judge it. If you have a ProgressDialog running in the thread, please cancel it in onDestroy, otherwise when the thread ends, Calling cancel of Dialog will throw an exception.

Under onpause, onstop and ondestroy, the Activity may be killed by the system.

Start another Activity and finish, first call the onPause method of the old Activity, then call the new Activity and onCreate->onStart->onResume method, then call the onStop->onDestroy method of the old Activity.

If finish is not called, the onDestroy method will not be called, and the onSavedInstanceState method will be called before onStop

After the onRestart method is executed, the onStart method is also called

fragment:[SupportFragmentManager,childFragment]

service:

[lifecycle of Android Service]

[difference between Android service and Thread]

Service and Intent Service: there is no difference, but the Intent Service starts a new HandlerThread in the onCreate method to execute.

Process and thread of Service: when it is running, if it is a LocalService, the corresponding Service is running on the main thread of the main process. Functions such as oncreate and OnStart are run on the main thread of the main process during system call. If it is RemoteSevice, the corresponding Service runs on a separate main thread.

  1. Services are not a single process. Services do not have their own processes. Applications can be different. Services run in the same process

  2. The service is not a thread and can work in a thread

  3. In an application, if it runs in the background for a long time and does not require interaction, use the service

  4. It is also run in the background without interaction. If only a task is completed, it does not need to be run later, and it may be multiple tasks that need to run for a long time

  5. If the task takes up a lot of CPU time and resources, threads should be used

The operation of the Thread is independent of the Activity, that is, after an Activity is finish ed, if you do not actively stop the Thread or the run method in the Thread is not completed, the Thread will be executed all the time.

8.2 painting mechanism

View drawing mainly involves three methods: onMeasure(), onLayout(), and onDraw()

  1. onMeasure is mainly used to calculate the size of the view, onLayout is mainly used to determine the position of the view in the ContentView, and onDraw is mainly used to draw the view.

  2. When executing onMeasure() and onLayout() methods, we will judge whether to execute the corresponding function through the corresponding flag bit or the corresponding coordinate point. For example, the invalidate method we often call will only execute the onDraw method, because the view size and position have not changed at this time, unless we call the requestLayout method to completely force the drawing of the view, To execute the above three methods.

Progress bar component:

[ProgressView]

[AnnotationView]

9. Event transmission mechanism

[android event handling mechanism summary, ScrollView ViewPager ListView GridView nested summary]

When the finger touches the screen, the system will call the onTouchEvent of the corresponding View and pass in a series of action s.

The execution order of dispatchTouchEvent is:

  1. First trigger the dispatchTouchEvent of ACTIVITY, and then trigger the onUserInteraction of ACTIVITY

  2. Then trigger the dispatchTouchEvent of LAYOUT, and then trigger the onInterceptTouchEvent of LAYOUT

This explains that super must be called when overriding ViewGroup dispatchTouchEvent();

(1)dispatchTouchEvent:

This method is generally used for preliminary processing of events. Because the action is distributed from this method, super. Is usually called dispatchTouchEvent. This will continue to call onInterceptTouchEvent, and then onInterceptTouchEvent will determine the flow direction of the event.

(2)onInterceptTouchEvent:

If the return value is true, the event will be passed to its own onTouchEvent(); If the return value is false, it will be passed to the dispatchTouchEvent() of the next View;

(3)onTouchEvent():

If the return value is true, the event is consumed by itself, and subsequent actions let it be processed; If the return value is false, you will not consume the event, and return upward to let the onTouchEvent of other parent views accept processing

Pseudo code of the relationship between the three methods: if the current View intercepts an event, it will be handed over to its own onTouchEvent for processing, otherwise it will be handed over to the child View to continue the same process.

public boolean dispatchTouchEvent(MotionEvent ev)

{

    boolean consume = false;

    if(onInterceptTouchEvent(ev))

    {

        consume = onTouchEvent(ev);

    }

    else

    {

        consume = child.dispatchTouchEvent(ev);

    }

    return consume;

} 

onTouchEvent delivery:

When there are multiple levels of views, if the parent level allows, this action will be passed until the deepest View is encountered. Therefore, the touch event first calls the onTouchEvent of the bottom View. If the onTouchEvent of the View receives a touch action and processes it accordingly, there are two return methods return true and return false; Return true will tell the system that the current View needs to handle this touch event and the action issued by the future system_ MOVE,ACTION_ Up still needs to continue listening and receiving, and the action has been processed this time. It is impossible for the View of the parent layer to trigger onTouchEvent. Therefore, at most one onTouchEvent interface can return true for each action. If false is returned, the system will be notified that the current View does not care about this touch event. At this time, this action will be passed to the parent and the onTouchEvent of the parent View will be called. However, if any action is issued after this touch event, the View will not accept it. onTouchEvent will never be triggered in this touch event, that is, once the View returns false, the subsequent ACTION_MOVE,ACTION_UP and other actions will not be passed into the View, but the action of the next touch event will still be passed in.

onInterceptTouchEvent of parent layer

As mentioned earlier, there is a precondition for the underlying View to receive this event: if the parent layer allows it. Assuming that the dispatch method of the parent level is not changed, the onInterceptTouchEvent method of the parent View will be called before the system calls the underlying onTouchEvent to determine whether the parent View wants to intercept the action after this touch event. If onInterceptTouchEvent returns true, all actions after this touch event will not be passed to the deep View, and all will be passed to the onTouchEvent of the parent View, that is, the parent layer has intercepted this touch event, and subsequent actions do not need to ask onInterceptTouchEvent, onInterceptTouchEvent will not be called for the action issued after this touch event until the next touch event. If oninterceptotouchevent returns false, this action will be sent to the deeper View, and each subsequent action will ask whether the oninterceptotouchevent of the parent layer needs to intercept this touch event. Only ViewGroup has onInterceptTouchEvent method, because an ordinary View must be the View in the deepest layer, and only ViewGroup has onInterceptTouchEvent method, because an ordinary View must be the View in the deepest layer, and the touch can be transferred here is the last stop, so it will definitely call the onTouchEvent() of View.

GetParent () of the underlying View requestDisallowInterceptTouchEvent(true)

For the underlying view, there is a way to prevent the parent view from getting the touch event, that is, calling getparent() Requestdisallowintercepttouchevent (true) method. Once the underlying View receives the action of touch, this method is called. Then the parent View will no longer call onInterceptTouchEvent, nor can it intercept subsequent action (if the parent layer ViewGroup and the bottom View need to intercept different focal points or touch with different gestures, this death can not be used).

There are two examples encountered in the development process: on the left is to handle the conflict between ViewPager and ListView, record the horizontal and vertical offsets, and let ViewPager handle pager sliding if there are more horizontal offsets

The sliding conflict between the ViewPager and ImageBanner processed on the right is also the recorded offset. If the horizontal offset on the ImageBanner is greater than the vertical offset, let the banner scroll

Think about why the dispatchTouchEvent method is overridden on the right instead of onInterceptTouchEvent method?

FixedViewPager

@Override

public boolean onInterceptTouchEvent(MotionEvent ev)

{

    switch(ev.getAction() & MotionEvent.ACTION_MASK)

    {

        case MotionEvent.ACTION_DOWN:

            mX = ev.getX();

            mY = ev.getY();

            break;

        case MotionEvent.ACTION_MOVE:

            float x = ev.getX();

            float y = ev.getY();

            float dX = x - mX;

            float dY = y - mY;

            float tmp = Math.abs(dX) / Math.abs(dY);

            mX = x;

            mY = y;

            if(tmp > 1)

            {

                return true;

            }

            else

            {

                return super.omInterceptTouchEvent(ev);

            }

    }

} 

FixedImageLoadBanner

@override

public boolean dispatchTouchEvent(MotionEvent ev)

{

if(mX != 0 || mY != 0)

{

    float dY = ev.getRawY() - mY;

    float dX = ev.getRawX() - mX;

    if(Math.abs(dY) > Math.abs(dX))

    {

        requestDisallowInterceptTouchEvent(false);

    }

    else

    {

        requestDisallowInterceptTouchEvent(true);

    }

}

mX = ev.getRawX();

mY = ev.getRawY();

return super.dispatchTouchEvent(ev);

}



[]( )10.ART and Dalvik difference

-----------------------------------------------------------------------------



art The application starts quickly and runs fast, but it consumes more storage space and takes a long time to install. In general ART The effect of is "space for time".



ART: Ahead of Time Dalvik: Just in Time



What is? Dalvik: Dalvik yes Google Designed by the company for Android Platform Java Virtual machine. Dalvik The virtual machine is Google And other manufacturers Android One of the core components of the mobile device platform, which can support the conversion to.dex(Namely Dalvik Executable)Formatted Java The operation of the application,.dex The format is designed for Dalvik A compression format designed for applications, suitable for systems with limited memory and processor speed. Dalvik It is optimized to allow multiple instances of virtual machines to run simultaneously in limited memory Dalvik Application as independent Linux Process execution. Independent processes can prevent all programs from being shut down when the virtual machine crashes.



What is? ART:Android The operating system is mature, Google of Android The team began to turn its attention to some of the underlying components, one of which is responsible for running the application Dalvik Runtime. Google Developers have spent two years developing faster, more efficient and power-saving alternatives ART Runtime. ART representative Android Runtime,It handles application execution in a completely different way Dalvik,Dalvik It depends on one Just-In-Time(JIT)The compiler interprets the bytecode. The developer's compiled application code needs to run on the user's device through an interpreter. This mechanism is not efficient, but it makes the application easier to run on different hardware and architectures. ART It completely changes this practice. When the application is installed, the bytecode is precompiled into the machine language. This mechanism is called Ahead-Of-Time(AOT)compile. After removing the interpreted code, the application will execute more efficiently and start faster.



ART advantage:



1.  Significant improvement of system performance

2.  Applications start faster, run faster, experience smoother, and feel feedback more timely.

3.  Longer battery life

4.  Support lower hardware



ART Disadvantages:



1.  Larger storage space occupation may increase by 10%-20%

2.  Longer application installation time



Scroller Three core methods in the execution process



1.  mScroller.startScroll()

2.  mScroller.computeScrollOffset()

3.  view.computeScroll()



1,stay mScroller.startScroll()Some initialization preparations are made for sliding, such as starting coordinates, sliding distance, direction and duration(There are default values),Animation start time, etc.



2,mScroller.computeScrollOffset()The main method is to calculate the current coordinate point according to the time that has elapsed. Because in mScroller.startScroll()If the animation time is set in computeScrollOffset()In the method, it is easy to get the position of the current time according to the elapsed time and save it in the variable mCurrX and mCurrY Yes. In addition, this method can also determine whether the animation has ended.



![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly91cGxvYWQtaW1hZ2VzLmppYW5zaHUuaW8vdXBsb2FkX2ltYWdlcy8yNDI0NDMxMy0zMjUxZDY1NzBhZmU1Y2I3LnBuZw?x-oss-process=image/format,png)



[]( )12.Activity Manager Service, ActivityThread

---------------------------------------------------------------------------------------------------------



[]( )13.Android Several processes

----------------------------------------------------------------------------



1.  Foreground process: the process that interacts with the user Activity perhaps Activity Used Service If the system memory is insufficient, the foreground process is the last to be killed

2.  Visible thread: it can be suspended(onPause)of Activity Or bound to it Service,That is, it is visible to the user, but it cannot interact with the user due to the loss of focus

3.  Service process: running in it startService Method started Service,Although it is not visible to the user, it is user related. For example, the user is listening to music in the non music interface or downloading files on the non download page. The system will be terminated when the system wants to run the first two processes in space

4.  Background process: in which execution is running onStop Method, but it is not the current concern of the user, such as the one hanging in the background QQ,Once such a process system has no memory, it will be killed first.

5.  Empty process: a process that does not contain program components of any application. Such a process system will not allow it to exist.



How to avoid background process being killed?



1.  call startForegound,Let your Service The process becomes the foreground process

2.  Service of onStartCommand return START\_STICKY or START\_REDELIVER\_INTENT

3.  Service of onDestroy Inside, restart yourself



[]( )14.Activity Startup mode

-----------------------------------------------------------------------------



standard:Activity The default loading method of the method will jump to a new one Activity,At the same time, push the instance onto the stack(Whatever Activity Already exists in Task Stack, are used new Operations, lifecycle from onCreate()start). For example, the order in the stack is A B C D,here D adopt Intent Jump to A,Then the structure in the stack becomes A B C D A,The display order of clicking the back button is D C B A,Destroy in turn.



singleTop:singleTop Mode, current Activity D At the top of the stack, if you pass Intent Jump to its own Activity(D),Then a new one will not be created D example(go onNewIntent()),So the structures in the stack are A B C D,If you jump to B,So because B Not at the top of the stack, so a new one will be created B Instance and pushed onto the stack, the structure becomes A B C D B. Application example: three push, click in is one Activity,It must work singletop



singleTask:singleTask In mode, Task There can only be one corresponding in the stack Activity example. For example: Task The structure in stack 1 is: A B C D. here D adopt Intent Jump to B(go onNewIntent()),The stack structure becomes:A,B. Among them C and D It is ejected and destroyed by the stack, that is, it is located in B All instances above have been destroyed. It is usually applied to the home page. The home page must be at the bottom of the stack and can only be at the bottom of the stack.



singleInstance:singleInstance In mode, the will be turned on Activity Push into a new task stack. For example: Task The structure in stack 1 is: A B C,C adopt Intent Jump to D(D The mode is singleInstance),Then a new one will be created Task,The structure in stack 1 is still A B C,The structure in stack 2 is D. The screen displays D,after D adopt Intent Jump to D,Stack 2 does not push new D,So the situation in the two stacks has not changed. If D Jump to C,Then it will be based on C Corresponding launchMode Perform corresponding operations in stack 1, C If yes standard,that D Jump to C,The structure of stack 1 is A B C C ,Click the back button at this time, or C,The structure of stack 1 becomes A B C,Instead of going back D. 



launchMode by singleTask When, through Intent Start to a Activity,If an instance already exists in the system, the system will send the request to the instance, but at this time, the system will not call the method we normally handle the request data onCreate Method instead of calling onNewIntent method.



onSavedInstanceState The call of follows an important principle, that is, when the system destroys your computer "without your permission" Activity,be onSavedInstanceState Will be called by the system, which is the responsibility of the system, because it must provide an opportunity for you to save your data onRestoreInstanceState Methods, it should be noted that, onSavedInstanceState Methods and onRestoreInstanceState Method 'not necessarily' is called in pairs.



onRestoreInstanceState The premise of being called is, Activity A It is indeed destroyed by the system, and if it just stays in the case of this possibility, the method will not be called, for example, when it is being displayed Activity A When the user presses HOME Key to return to the main interface, and then the user returns to the Activity A,In this case Activity A Generally, it will not be destroyed due to memory, so Activity of onRestoreInstanceState Method will not be executed.



In addition, onRestoreInstanceStated of bundle Parameters are also passed to the onCreate In the method, you can also choose onCreate Method.



onSavedInstanceState(Bundle bundle)Usually and onRestoreInstanceState(Bundle bundle)Not in pairs, onRestoreInstanceState This thing doesn't trigger very well. I'll give you a good way. When switching between horizontal and vertical screens, it's 100%Will trigger. Then save in onRestoreInstanceState bundle The data inside is onCreate The parameter of bundle Well, how to recover depends on the developer.



[]( )15.TMImageView Design of picture library

----------------------------------------------------------------------------------



Feature mechanism



[]( )16.ListView optimization

---------------------------------------------------------------------------



1.  First of all, although we all know, we should mention it and make good use of it convertView To reuse View,Never every time getView All new. ListView The core principle of is reuse View. ListView There's a recycler, Item When sliding out of the interface view It will be recycled here and a new one needs to be displayed Item When, try to reuse the garbage in the collector View. 

2.  Make good use of ViewType,Like yours ListView There are several types of Item,You need to create different for each type View,This is good for ListView Of course, there can't be too many types of recycling

3.  Try to make ItemView of Layout The hierarchy is simple, and all Layout Must be observed

4.  Make good use of customization View,custom View Can effectively reduce Layout Level, and the drawing process can be well controlled

5.  Try to ensure Adapter of hasStableIds()return true,So in notifyDataSetChanged()When, if id unchanged, listView This will not be redrawn View,Achieve the purpose of optimization.

6.  each item Not too high, especially not beyond the height of the screen, you can refer to Facebook The optimization method is particularly complex Item Decompose into several small Item.

7.  To ensure ListView The smoothness of sliding, getView()Try to do as few things as possible and do not have time-consuming operations. Especially when sliding, don't load pictures. Stop and load again.

8.  use RecyclerView Replace. ListView Update the data every time notifyDataSetChanged(),Some are too violent. RecyclerView The performance and customizability have been greatly improved. It is recommended to use.

9.  Sometimes, you need to fundamentally consider whether you really want to use it listView To meet your needs, or are there other options?



[]( )17.webView

------------------------------------------------------------------------



How to use webview stay js Call in java method?



webView.addJavaScriptInterface(new Object(){xxx}, "xxx");



Answer: Yes WebView Control execution JavaScript Script, and you can JavaScript Medium execution Java code. To make WebView Control execution JavaScript,Need to call WebSettings.setJavaScriptEnabled Method, the code is as follows:



WebView webView = (WebView)findViewById(R.id.webview)

WebSettings webSettings = webView.getSettings()

//Set WebView to support JavaScript

webSettings.setJavaScriptEnabled(true)

webView.setWebChromeClient(new WebChromeClient())



JavaScript call Java Method needs to be used WebView.addJavascriptInterface Method settings JavaScript Invoked Java Method, the code is as follows:



webView.addJavascriptInterface(new Object()

{

public String process(String value)

{



    return result;

}

}, "demo");



You can use the following JavaScript Code call process Method, the code is as follows:



function search()

{



    result.innerHTML = "" + window.demo.process('data') + "";

} 


[]( )18.SurfaceView and View The most essential difference between

----------------------------------------------------------------------------------------



SurfaceView It is possible to redraw the picture in a new separate thread, and view Must be UI Update the screen in the main thread of.



stay UI Updating the screen in the main thread of may cause problems. For example, if you update for too long, your main thread UI The thread will be blocked by the function you are drawing. Then you will not be able to respond to key, touch screen and other messages. When used SurfaceView Since the screen is updated in a new thread, it won't block you UI Main thread. But this also brings another problem, that is, event synchronization. For example, if you touch the screen, you need to SurfaceView in thread Processing, generally need to have a event queue Save your design touchevent,This is a little more complicated because it involves thread safety.



[]( )19.label

-------------------------------------------------------------------



\[merge and include\]



\[Android ViewStub Basic use of\]  

In short, they are all used to solve the problem of repeated layout, but labels can be reduced when layout is reused UI Hierarchy.  

viewStub Labels are used for other View Occupy a good position in advance and use it when necessary inflater()Or setVisible()Method to display these View. 



[]( )20.ANR Troubleshooting

----------------------------------------------------------------------



1,ANR There are generally three types of troubleshooting



1.  KeyDispatchTimeout(5 seconds) –The main type of key or touch event has no response within a specific time

2.  BroadcastTimeout(10 secends) –BroadcastReceiver Processing cannot be completed within a specific time

3.  ServiceTimeout(20 secends) –Small probability event Service Processing cannot be completed within a specific time



2,How to avoid



1.  UI Threads try to do only with UI Related work

2.  Time consuming operation(For example, database operations, I/O,The connection to the network or others may be blocked UI Thread operation)Put it in a separate thread

3.  Try to use Handler To handle UIthread And others thread Interaction between



3,How to check



1.  First analysis log

2.  from trace.txt File view call stack,adb pull data/anr/traces.txt ./mytraces.txt

3.  Look at the code

4.  go through ANR Cause of formation(iowait?block?memoryleak?)



4,monitor ANR of Watchdog



[]( )21.fragment life cycle

-----------------------------------------------------------------------------



\[Picture uploading(image-4517e1-1597835878604-0)\]



Common interview questions\=========



**1,When switching between horizontal and vertical screens Activity Life cycle of**



1.  Not set Activityd hungry android:configChanges When the screen is cut, it will fall off again. It will be executed once when cutting the horizontal screen and twice when cutting the vertical screen

2.  set up Activity of android:configChanges="orientation"When the screen is switched, each life cycle will still be called, and switching between horizontal and vertical screens will only be executed once

3.  set up Activity of android:configChanges="orientation|keyboardHidden"During screen cutting, each life cycle will not be called again, but only executed onConfigurationChanged method



**2,(Picture related)OOM How to deal with it?**



\[Android Memory overflow solution( OOM) Finishing summary\]



1.  Do some processing on memory references, such as soft references and weak references

2.  When loading pictures in memory, they are processed directly in memory, such as boundary compression

3.  Dynamically reclaim memory

4.  optimization Dalvik Heap memory allocation for virtual machines
# Epilogue

In a twinkling of an eye, time really flies. We went our separate ways and embarked on our own journey, but even if we haven't seen each other for many years, we are still as "close" as before because of this friendship. Never forget the original heart. Come on, programmers, in my opinion, 35 and 40 are never a crisis, as long as you never forget why you embarked on the journey!

#### **[CodeChina open source project: Android learning notes summary + mobile architecture Video + big factory interview real questions + project actual combat source code]( https://codechina.csdn.net/m0_60958482/android_p7)**

In order to let more friends who are studying or are preparing for an interview see this article, I hope you can comment and praise it+forward!

**Thank you again for all the friends who have provided me with questions. Thank you all the way!**

Keywords: Android Design Pattern Interview

Added by turek on Fri, 17 Dec 2021 08:35:25 +0200