A summary of the super-complete Android common interview questions gathered from nearly forty interviews

This article sorts out nearly 40 interview questions from friends around me, and adds my own understanding and some wonderful comments in the article. All articles are not original

Interview questions:

1. Talk about the process of customizing LayoutManager?

  • Determine Itemview's LayoutParamsgenerateDefaultLayoutParams
  • Determine the position of all itemviews in recyclerview, and recycle and reuse itemviewonLayoutChildren
  • Add sliding canScrollVertically

2. What is RemoteViews? What are the usage scenarios?

RemoteViews is translated as remote view. As the name suggests, RemoteViews is not the View of the current process, but belongs to the SystemServer process. The application and RemoteViews rely on Binder to realize inter-process communication.

Usage: usually in the notification bar

//1.创建RemoteViews实例
RemoteViews mRemoteViews=new
RemoteViews("com.example.remoteviewdemo", R.layout.remoteview_layout);
//2.构建一个打开Activity的PendingIntent Intent
intent=new
Intent(MainActivity.this,MainActivity.class);
PendingIntent
mPendingIntent=PendingIntent.getActivity(Main
Activity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
//3.创建一个Notification
mNotification = new
Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(mPendingIntent)
.setContent(mRemoteViews)
.build();
//4. 获 取 NotificationManager
manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE
);
Button button1 = (Button)
findViewById(R.id.button1);
button1.setOnClickListener(new
OnClickListener() {
@Override
public void onClick(View v) {
//弹出通知
manager.notify(1, mNotification);
}
});

3. Talk about several ways to get the width and height of View?

  • OnGlobalLayoutListener gets
  • OnPreDrawListener gets
  • OnLayoutChangeListener gets
  • Rewrite View's onSizeChanged()
  • Use the View.post() method

4. Talk about interpolators and estimators?

  • An interpolator that calculates
    the percentage of a property's change based on the percentage of time (animation times) elapsed. By default, there are constant speed, acceleration and deceleration, and deceleration interpolators.
  • The estimator, which calculates
    the value of the specific change through the percentage obtained by the interpolator above. The system defaults are integer, floating point, and color estimators
  • Customizations only need to override their evaluate method.

5. What is the difference between getDimension, getDimensionPixelOffset and getDimensionPixelSize?

The same point: when the unit is dp/sp, it will be multiplied by density, and if the unit is px, it will not be multiplied

difference:

  • getDimension returns a float value
  • getDimensionPixelSize, returns an int value, when converting float to int, round up
  • getDimensionPixelOffset, returns an int value, when converting float to int, round down (i.e. ignore decimal values)

6. Regarding LayoutInflater, how does it obtain a specific View through the inflate method?

The system creates a layout constructor through LayoutInflater.from. In the inflate method, it will finally use createViewFromTag. Here it will judge the two parameters factory2 and factory. If both are empty, the system will create a view by itself, and through an xml parser, get Label name, and then judge whether it is <Button or xxx.xxx.xxView. Then go to createView to get the full class name path through splicing, and create a class by reflection.

7. Talk about the caching mechanism of RecyclerView?

scrap viewCacherecyclerPool:
scrap is the currently displayed cache, and the cached viewCache is an invisible cache outside the screen during onlayout. You can set the viewCache to be larger, and change the space for time to avoid fast sliding within a certain distance. The above two caches do not use createView and onbind recyclerPool is special. It will go onbind. It can be shared by multiple recyclerViews. The actual use is: share items between multiple recyclerViews, apply horizontal recyclerView embedded in vertical recyclerView, or multiple recyclerViews in viewpager

8. Please talk about the difference between View.inflate and LayoutInflater.inflate?

practically no difference

  • View.inflate is actually a layer of packaging for LayoutInflater.inflate. Functionally, LayoutInflate is more powerful.
  • View.inflate actually finally calls the method of LayoutInflater.inflate(@LayoutRes int resource, @nullable ViewGroup root) with three parameters. If the root passed in here is not empty, the parsed View will be added to this Go among the ViewGroup.
  • The LayoutInflater.inflate method can specify whether the current View needs to be added to the ViewGroup

9. Please talk about the difference and application scenarios between the invalidate() and postInvalidate() methods?

  • invalidate() is used to redraw the UI and needs to be called on the UI thread.
  • postInvalidate() is also used to redraw the UI. It can be called in the UI thread or in a sub-thread. The postInvalidate() method sends a message through the Handler to switch the thread back to the UI thread to notify the redrawing, not to say postInvalidate() can update the UI in the child thread, essentially redrawing occurs on the UI thread, but we use postInvalidate() which will help us switch threads internally

10. Talk about the usage scenarios and usage of SurfaceView and TextureView?

  • Frequent drawing and high frame rate requirements, such as taking pictures, videos and games, etc.
  • SurfaceView has an independent drawing surface, which can be drawn in sub-threads.
    The disadvantage is that it cannot perform translation, scaling, rotation, and transparent gradient operations. The emergence of TextureView is to solve these problems.
  • The use of SurfaceView is probably to obtain the SurfaceHolder object, monitor the surface creation, update, destruction, create a new thread, and draw and submit it in it
  • TextureView does not have an independent drawing surface. During use, you need to add a monitor to see if surfaceTexture is available, and then do corresponding processing

11. Talk about the difference between several refreshing methods of RecyclerView.Adapter?

Refresh all visible items, notifyDataSetChanged() refreshes the specified item, notifyItemChanged(int)
refreshes the specified item from the specified position, notifyItemRangeChanged(int,int) inserts, moves one and refreshes automatically, notifyItemInserted(int), notifyItemMoved(int), notifyItemRemoved(int) partial refresh, notifyItemChanged(int, Object)

12. Have you heard about WindowInsets? What are its applications?

ViewRootImpl will call dispatchApplyInsets when performing Traversals, and internally call DecorViewdispatchApplyWindowInsets to distribute WindowInsets.

Thirteen, talk about the screen refresh mechanism?

Screen refresh frequency and drawing frequency cpu is responsible for measurelayoutdraw => displayList gpu is responsible for display => bitmap will send a vertical synchronization signal every 16ms, and vsync will take out the rendered bitmap from the gpu buffer every time the signal is sent and display it on the screen At the same time, if necessary, the next cpu calculation will be performed, and the calculation will be put into the buffer. If the calculation time exceeds the time between two vsyncs, that is, 16ms, the vsync signal will put the previous gpu buffer When the information is displayed, it is stuck at this time. In addition, if the page does not change, the screen will still go to the buffer to take out the last refresh, but the CPU will no longer calculate it.

14. What are the ways to use multithreading in Java?

There are roughly four types:
extends Thread; implRunnable; implCallable creates threads through the FutureTask wrapper; uses ExecutorService, Callable, and Future to implement multi-threading with return results. ;Threads that extend Thread and implRunnable have no return value, while FutureTask ExecutorService(ExecutorService.submit(xxx) return Future<?> ) has a return value

15. Tell me about several states of threads?

The first is to create state. When the thread object is generated, the start method of the object is not called, which means that the thread is in the created state.

The second is the ready state. When the start method of the thread object is called, the thread enters the ready state, but at this time the thread scheduler has not set the thread as the current thread, so it is in the ready state. After the thread runs, after returning from waiting or sleeping, it will also be in the ready state.

The third is the running state. The thread scheduler sets the thread in the ready state as the current thread. At this time, the thread enters the running state and starts running the code in the run function.

The fourth is the blocking state. When a thread is running, it is suspended, usually to wait for a certain time to happen (for example, a resource is ready) before continuing to run. Sleep, suspend, wait and other methods can cause thread blocking.

The fifth is the state of death. If a thread's run method ends or the stop method is called, the thread will die. For a dead thread, the start method can no longer be used to make it ready.

16. How to achieve synchronization in multithreading?

Synchronous and asynchronous multithreading are not the same thing. Several situations,
1. It is what everyone calls synchronized, which can guarantee atomicity and ensure that only one thread can hold the lock when multiple threads operate the same method, and operate this method. 2. Manually call the read-write
lock
3. Manually The wait and notify of the operating thread
4. volatile I remember is not atomic, it can guarantee memory visibility, and in the case of multi-threading, ensure that the data of each thread is up-to-date

Seventeen, the definition of deadlock

Multithreading and multiprocessing improve the utilization of system resources and increase the processing capacity of the system. However, concurrent execution also brings a new problem - deadlock. The so-called deadlock refers to a deadlock (waiting for each other) caused by multiple threads competing for resources. If there is no external force, these processes will not be able to move forward.

Eighteen, the cause of deadlock

  1. Competition for system resources 2. The sequence of process advancement is not 3. Improper use of semaphores can also cause deadlocks.

Nineteen, the necessary conditions for deadlock

Mutually exclusive conditions: The process requires exclusive control over allocated resources (such as printers), that is, a resource is only occupied by one process within a period of time.
At this time, if other processes request the resource, the requesting process can only wait.

Non-deprivation condition: The resource obtained by the process cannot be forcibly taken away by other processes before it is used up, that is, it can only be released by the process that obtained the resource itself (only active release).

Request and holding conditions: The process has held at least one resource, but it proposes a new resource request, and the resource is already occupied by other processes. At this time, the requesting process is blocked, but it does not let go of the resources it has obtained.

Circular waiting condition: There is a circular waiting chain of process resources, and the resource obtained by each process in the chain is simultaneously requested by the next process in the chain.

20. The efficiency of hardware

It is impossible for a computer processor to handle most of the running tasks by only relying on the "calculation" of the processor. The processor needs to interact with the memory at least, such as reading calculation data and storing calculation results. This I/O operation is difficult to eliminate ( It is impossible to complete all calculation tasks with registers alone).
Since there is a gap of several orders of magnitude between the computing speed of the computer's storage device and the processor, in order to prevent the processor from waiting for the slow memory read and write operations to complete,
modern add a layer of read and write speed as close as possible to the processor's computing speed cache. The cache acts as a buffer between the memory and the processor: copy
the data needed for the operation to the cache, so that the operation can run quickly, and then synchronize from the cache back to the memory after the operation is completed.

21. Cache consistency problem

The cache-based storage system interaction solves the contradiction between processor and memory speed well, but it also brings higher complexity to the computer system, because it introduces
a new problem: cache coherence.
In a multi-processor system (or a single-processor multi-core system), each processor (each core) has its own cache, and they share the same main memory (Main Memory). When the calculation tasks of multiple processors all involve the same main memory area, it may cause inconsistency in their respective cache data. To this end, each processor needs to follow some protocols when accessing the cache, and operate according to the protocol when reading and writing to maintain the consistency of the cache.

22. Code out-of-order execution optimization problem

In order to make full use of the computing units inside the processor and improve computing efficiency, the processor may execute the input code out of order, and the processor will
reorganize the results of the out-of-order execution after calculation. Out-of-order optimization can ensure that The execution result under single thread is consistent with the result of sequential execution, but it does not guarantee that the
order of calculation of each statement in the program is consistent with the order in the input code.

Twenty-three, the composition of the Java memory model

Main memory: The Java memory model stipulates that all variables are stored in the main memory (Main Memory). a part of).

Working memory: Each thread has its own working memory (Working Memory, also known as local memory, which can be compared with the processor cache introduced earlier), and the working memory of the thread stores the variables used by the thread in the main memory A copy of the shared variable. Working memory is an abstraction of JMM and does not really exist. It covers caches, write buffers, registers, and other hardware and compiler optimizations.

24. Concurrency issues of JVM memory operations

1. Consistency of working memory data When each thread operates data, it will save the copy of the shared variable in the main memory used. When the calculation tasks of multiple threads involve the same shared variable, the respective copies of the shared variable will be inconsistent. If this happens, whose copy data shall prevail when the data is synchronized back to the main memory? The Java memory model mainly ensures data consistency through a series of data synchronization protocols and rules, which will be introduced in detail later.

2. Instruction reordering optimization In Java, reordering is usually a method for reordering and executing instructions adopted by the compiler or runtime environment to optimize program performance. There are two types of reordering: compile-time reordering and runtime reordering, corresponding to compile-time and runtime environments, respectively. Similarly, instruction reordering is not random reordering. It needs to meet the following two conditions:
1) The result of program running cannot be changed in a single-threaded environment. The just-in-time compiler (and processor) needs to ensure that the program can comply with as-if-serial Attributes. In layman's terms, it is to give the program an illusion of sequential execution in the case of single thread. That is, the reordered execution results must be consistent with the sequential execution results.
2) Reordering is not allowed if there is a data dependency. In a multi-threaded environment, if there is a dependency between thread processing logic, the running result may be different from the expected result due to the reordering of instructions. Later, we will expand how the Java memory model solves this problem. Condition.

Twenty-five, talk about the Activity life cycle?

Under normal circumstances, the common life cycle of Activity is only the following 7

  • onCreate(): Indicates that the Activity is being created, and is often used to initialize work, such as calling setContentView to load interface layout resources, initialize the data required by the Activity, etc.;
  • onRestart(): Indicates that the Activity is restarting. Under normal circumstances, OnRestart will be called when the current Acitivty changes from invisible to visible again;
  • onStart(): Indicates that the Activity is being started. At this time, the Activity is visible but not in the foreground. It is still in the background and cannot interact with the user;
  • onResume(): Indicates that the Activity has gained focus, and at this time the Activity is visible and in the foreground and starts active, which is the difference from onStart;
  • onPause(): Indicates that the Activity is stopping. At this time, you can do some work such as storing data and stopping animation, but it should not be too time-consuming, because it will affect the display of the new Activity. OnPause must be executed first, and the onResume of the new Activity will not implement;
  • onStop(): Indicates that the Activity is about to stop, and you can do some heavyweight recycling work, such as canceling the broadcast receiver, closing the network connection, etc., and it should not be too time-consuming;
  • onDestroy(): Indicates that the Activity is about to be destroyed. This is the last callback in the Activity life cycle, often doing recycling work and resource release;

26. What methods will be called when Activity A starts another Activity B? What if B is a transparent theme or a DialogActivity?

Activity A starts another Activity B, and the callback is as follows:
onPause() of Activity A → onCreate() of Activity B → onStart() → onResume() → onStop() of Activity A;
if B is a transparent theme or a DialogActivity, Then A's onStop will not be called back;

27. Tell me about the function of the onSaveInstanceState() method? When will it be called?

Occurrence conditions: under abnormal circumstances (Activity is killed and recreated when system configuration changes, low-priority Activity is killed due to insufficient resource memory)

  • The system will call onSaveInstanceState to save the state of the current Activity. This method is called before onStop and has no established timing relationship with onPause;
  • When the Activity is rebuilt, the system will call onRestoreInstanceState, and pass the Bundle object saved by the onSave (abbreviation) method to onRestore (abbreviation) and onCreate() at the same time, so these two methods can be used to determine whether the Activity has been rebuilt,
    call after onStart;

Twenty-eight, talk about the four startup modes and application scenarios of Activity?

Standard standard mode: every time an Activity is started, a new instance will be recreated, regardless of whether the instance already exists
, the Activity in this mode will enter the task stack of the Activity that started it by default;
singleTop stack top multiplexing mode: if If the new Activity is already at the top of the task stack, the Activity will not be recreated, and the onNewIntent method will be called back. If the new Activity instance already exists but is not at the top of the stack, the Activity will still be recreated;

SingleTask in-stack multiplexing mode: As long as the Activity exists in a task stack, the instance will not be
recreated and the onNewIntent method will be called back. In this mode, when Activity A is started, the system will first look for whether there is an activity A wants If the task
stack does not exist, a task stack will be recreated, and then the created instance of A will be placed on the stack;
singleInstance single instance mode: This is an enhanced singleTask mode, and the Activity with this mode can only Separately located
in a task stack, and there is only one instance in this task stack;

29. Know which flags are commonly used in activities?

  • FLAG_ACTIVITY_NEW_TASK : corresponds to the singleTask startup mode, and its effect is the same as specifying the startup mode in XML;
  • FLAG_ACTIVITY_SINGLE_TOP : corresponds to the singleTop startup mode, and its effect is the same as specifying the startup mode in XML;
  • FLAG_ACTIVITY_CLEAR_TOP : When an Activity with this flag is started, all activities above it in the same task stack will be popped out. This flag usually appears together with the singleTask mode. In this case,
    if the instance of the started Activity already exists, the system will call back onNewIntent. If the started Activity is
    started in standard mode, it and the activities above it will be popped out of the stack, and the system will create a new Activity instance and put it in the stack;
  • FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS : Activities with this flag will not appear in the history activity list
    ;

30. How to start the Activity of other applications?

In the case of guaranteed access, use the implicit Intent to match the IntentFilter of the target Activity. The principle is:
an intent can only be started if it matches the action, category, and data in the intent-filter of an Activity at the same time. Activity;
an Activity can have multiple intent-filters, as long as an intent successfully matches any set of intent-filters, the Activity can be started;

31. Talk about the life cycle of Fragment?

The methods involved in the entire life cycle of Fragment from creation to destruction are: onAttach()→onCreate()→onCreateView()→onActivityCreated()→onStart()→onResume()→onPause()→onStop()→onDestroyView( )→onDestroy()→onDetach(), there are many methods with the same name and similar function as Activity, but the different methods
are:

  • onAttach(): Called when Fragment and Activity are associated;
  • onCreateView(): called when the fragment creates a view, after onCreate;
  • onActivityCreated(): Called when the Activity associated with the Fragment completes onCreate();
  • onDestroyView(): Called when the layout in the Fragment is removed;
  • onDetach(): Called when Fragment and Activity are disassociated;

Thirty-two, talk about the difference between Activity and Fragment?

Similarities: Both can contain layouts and have their own life cycle

difference:

  • Compared with Activity, Fragment has 4 more callback cycles, which is more flexible in control operation;
  • Fragment can be written directly in the XML file, or dynamically added in the Activity;
  • Fragment can use show()/hide() or replace() to switch Fragment at any time, and there will be no obvious effect when switching, and the user experience will be better; although Activity can also be switched, there will be some problems when switching between Activities. Obvious page turning or other effects do not give users a good feeling when switching a small part of content;

Thirty-three, the difference between add and replace in Fragment (Fragment overlaps)

  • add will not reinitialize the fragment, replace will every time. So if you get the data in the fragment life cycle, you will get it repeatedly if you use replace;
  • When adding the same fragment, there will be no change in replace, and add will report an IllegalStateException;
  • Replace first removes all fragments with the same id, and then adds the current fragment, while add overwrites the previous fragment. So if you use add, it will generally be accompanied by hide() and show() to avoid layout overlap;
  • Using add, if the app is placed in the background or destroyed by the system in other ways, when it is opened again, the fragment referenced in hide() will be
    destroyed so there will still be layout overlapping bugs, you can use replace or add one when using add tag parameter;

Thirty-four, the difference between getFragmentManager, getSupportFragmentManager, getChildFragmentManager?

  • What getFragmentManager() gets is the manager of the parent container of the fragment where it is located, and what getChildFragmentManager() gets is the manager of the sub-container in the fragment. If the fragment is a nested fragment, then you need to use getChildFragmentManager();
  • Because Fragment is a component that only appears in the 3.0 Android system API version, the system above 3.0 can directly call getFragmentManager() to obtain the FragmentManager() object, while the system below 3.0 needs to call getSupportFragmentManager() to obtain it indirectly;

Thirty-five, the difference between FragmentPagerAdapter and FragmentStatePagerAdapter and usage scenarios

The same point: both inherit PagerAdapter

The difference: each Fragment of FragmentPagerAdapter will be persistently stored in FragmentManager, and it will not be destroyed as long as the user can return to the page. Therefore, it is suitable for pages with relatively static data and a relatively small number of Fragments; FragmentStatePagerAdapter only retains the current page, and when the page is invisible, the Fragment will be eliminated and its resources will be released. Therefore, it is suitable for situations where the data is more dynamic, takes up more memory, and has many Fragments;

postscript

It took me a lot of energy to sort out this interview question. It seems a bit clumsy to copy the interview questions after reviewing the questions. And in order not to look so clumsy, I specifically thought about the questions I usually see and consulted relevant materials for the questions mentioned by the author, and put these materials under the corresponding interview questions. The original intention of organizing this article is to deal with the interviewer, but the more I look at it, the more I feel that I lack more, so whether it is the interview experience shared by the author or the technical details shared by the author are so precious to me! This process is just like when we went to school. At the beginning, it was to meet the requirements of teachers and parents, but as I grew up, I realized that the gains in this process were far greater than the requirements of teachers and parents.

Finally, the reason for the space is here. I try to make up for the shortcomings mentioned in the interview questions. I also hope that everyone who reads here can find a satisfactory job or find what they want in the article. ! If you still need to know more about the analysis of the answers to Android interview questions, you can get the card at the end of the article

It's not easy to organize, your likes, watching, reposting, and star marks are my greatest encouragement! I wish everyone can get a satisfactory offer!

insert image description here

Guess you like

Origin blog.csdn.net/Androiddddd/article/details/131963594