Android interview questions (latest in 2023)

Disclaimer: Some people say that some interview questions are abnormal. Personally, I think it is because our foundation is not solid or in-depth. This article comes from a very senior senior's summary of the recent Android interview questions. There are 1600+ questions and a wide range of knowledge. Moreover, this senior has given answers to each question by himself. If you If you have questions or don’t understand a certain question, you can log in on the computer to copy the topic and post a comment for everyone to discuss together, or you can follow me and send me a private message after logging in on the computer, let’s make progress together!

Activity

1. 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;

2. 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;

3. 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;

4. Tell me 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;

5. 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 into the stack;
  • FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS : Activities with this flag will not appear in the history activity list
    ;

6. 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;

Fragment interview questions

1. 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;

2. 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;

3. 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;

4. What is the difference between getFragmentManager, getSupportFragmentManager and 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 indirectly;

5. 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 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;

Service interview questions

1. Talk about the life cycle of Service?

  • onCreate(): If the service has not been created, the onCreate() callback will be executed after calling startService(); if the service is already
    running, calling startService() will not execute the onCreate() method. In other words, onCreate() will only be created for the first time
  • Called during service, multiple executions of startService() will not call onCreate() repeatedly, this method is suitable for completing some initialization work;
  • onStartCommand(): Called when the service starts, this method is suitable for completing some data loading tasks, such as creating a thread here for downloading data or playing music;
  • onBind(): Called when the service is bound;
  • onUnBind(): called when the service is unbound;
  • onDestroy(): called when the service stops;

2. Two ways to start the Service? Where is the difference?

Two startup modes of Service:

  • startService(): By calling startService in this way, onCreate() will only be called once, and calling startServie multiple times
    will execute the onStartCommand() and onStart() methods multiple times. If the stopService() or stopSelf() method is not called externally,
    the service will keep running.
  • bindService(): If the service has not been created before, the system callback sequence is onCreate()→onBind(). If the service has been bound before calling the bindService() method, calling the bindService() method multiple times will not create the service and bind it multiple times. If the caller wants to unbind from the service being bound, he can call the unbindService() method, and the callback sequence is onUnbind()→onDestroy();

3. How to ensure that the Service is not killed?

  • In the onStartCommand method, return START_STICKY or START_REDELIVER_INTENT

START_STICKY : If START_STICKY is returned, it means that after the running process of the Service is forcibly killed by the Android system, the Android system will still set the Service to the started state (that is, the running state), but will no longer save the intent object passed in by the onStartCommand method

START_NOT_STICKY : If START_NOT_STICKY is returned, it means that the Service will not be recreated after the running process of the Service is forcibly killed by the Android system

START_REDELIVER_INTENT : If START_REDELIVER_INTENT is returned, its return is similar to START_STICKY, but the difference is that the system will retain the Intent that was last passed into the onStartCommand method and then pass it into the recreated Service onStartCommand method again.

  • Increase the priority of Service. In the AndroidManifest.xml file, the intent-filter can
    set the highest priority through the attribute android:priority = "1000", and 1000 is the highest value. If the number is smaller, the priority is lower, and it is also suitable for broadcasting;
  • Restart the Service in the onDestroy method When the service reaches onDestroy(), send a custom broadcast, and
    restart the service when the broadcast is received;
  • Increase the priority of the Service process. Process priority from high to low: foreground process-visual process-service process-background process-
    empty process can use startForeground to put the service in the foreground state, so that when the memory is low, the probability of being killed will be lower;
    system broadcast monitoring Service state installs the APK to /system/app and turns it into a system-level application

4. Can time-consuming operations be enabled in the Service? How to do it?

Service does not run in a child thread by default, nor does it run in an independent process, it also executes in the main thread (UI thread). In other words, do not perform time-consuming operations in the Service, unless a child thread is manually opened, otherwise the main thread may be blocked (ANR);

5. What system services have you used?

alt

6. Do you understand ActivityManagerService? What role does it play?

ActivityManagerService is the core service in Android. It is mainly responsible for the startup, switching, scheduling of the four major components in the system and the management and scheduling of application processes. Its responsibilities are similar to the process management and scheduling modules in the operating system;

IPC interview questions

1. What is the relationship between process and thread in Android? the difference?

  • A thread is the smallest unit of CPU scheduling, and a thread is a limited system resource;
  • A process generally refers to an execution unit, a program or an application on a PC and a mobile device,
  • Generally speaking, an App program has at least one process, and a process has at least one thread (the relationship between contained and contained). Generally speaking, there is a process in the App factory, and the thread is the production line inside, but the main thread There is only one (main production line), but there can be multiple sub-threads (secondary production lines).
  • A process has its own independent address space, and the threads in the process share this address space and can execute concurrently.

2. How to enable multi-process? Can an application open N processes?

  • Specify the attribute android:process for the four major components in AndroidMenifest to enable multi-process mode
  • N processes can be opened under the condition of memory permitting

3. Why is IPC needed? What problems may arise in multi-process communication?

  • All the four major components (Activity, Service, Receiver, ContentProvider) running in different processes will
    fail . This is because Android allocates an independent virtual machine for each application, and different virtual machines have different memory allocations. Address space, which will result in multiple copies of objects of the same class accessed in different virtual machines. For example, common examples (obtaining more memory space by enabling multiple processes, sharing data between two or more applications, WeChat Family Bucket)
  • Generally speaking, the use of multi-process communication will cause the following problems

1) Static members and singleton patterns are completely invalid: independent virtual machines cause

2) The thread synchronization mechanism is completely effective: independent virtual machines cause

3) The reliability of SharedPreferences decreases: this is because Sp does not support two processes to read and write concurrently, which may lead to data loss

4) Application will be created multiple times: the Android system will allocate an independent virtual machine when creating a new process, so this process is actually the process of starting an application, and naturally a new Application will be created

4. What is the function and principle of Binder mechanism?

The Linux system divides a process into user space and kernel space. For processes, the data in user space cannot be shared, but the data in kernel space can be shared. In order to ensure security and independence, one process cannot directly operate or access another process, that is, Android processes are independent and isolated from each other. , which requires a data communication method across processes.

A complete Binder IPC communication process is usually like this:

  • First, the Binder driver creates a data receiving buffer in the kernel space;
  • Then open up a kernel buffer area in the kernel space, establish the mapping relationship between the kernel buffer area and the data receiving buffer area in the kernel, and the mapping relationship between the data receiving buffer area in the kernel and the user space address of the receiving process;
  • The sender process copies the data to the kernel buffer in the kernel through the system call copyfromuser(). Since there is a memory mapping between the kernel buffer and the user space of the receiving process, it is equivalent to sending the data to the user space of the receiving process. An inter-process communication is completed.

5. Why does the Bundle transfer object need to be serialized? What is the difference between Serialzable and Parcelable?

  • Because the bundle only supports basic data types when transferring data, it needs to be serialized and converted into a storable or transferable
    essential state (byte stream) when transferring objects. Serialized objects can be
    transferred between networks, IPC (such as Activity, Service, and Receiver that start another process), and can also be stored locally.
  • Two ways of serialization implementation: implement the Serializable/Parcelable interface. The difference is shown in the figure:

alt

6. Tell me about AIDL? What is the principle? How to optimize the situation where multiple modules use AIDL?

  • AIDL (Android Interface Definition Language, Android Interface Definition Language): If you want to call the method of an object in another process in one process, you can use AIDL to generate serializable parameters, and AIDL will generate a proxy class for the server object, through Its client implements methods that indirectly call server-side objects.

  • The essence of AIDL is that the system provides a set of tools that can quickly implement Binder. Key classes and methods:

1) AIDL interface: Inherit IInterface.

2) Stub class: the implementation class of Binder, through which the server provides services.

3) Proxy class: the local proxy of the server, through which the client calls the method of the server.

4) asInterface(): Called by the client to convert the Binder object returned by the server into the AIDL interface type object required by the client. If the client and server are in the same process, return the Stub object itself directly, otherwise return the Stub.proxy object encapsulated by the system

5) asBinder(): Return the Binder object of the proxy Proxy according to the current call situation.

6) onTransact(): In the Binder thread pool running the server, when the client initiates a cross-process request, the remote request will be encapsulated by the bottom layer of the system and handed over to this method for processing.

7) transact(): runs on the client, and suspends the current thread when the client initiates a remote request. After that, the onTransact() of the server is called until the remote request returns, and the current thread continues to execute.

  • When multiple business modules require AIDL to perform IPC, a specific aidl file needs to be created for each module, and there will be
    many corresponding services. There will inevitably be serious system resource consumption and excessive heavyweight applications. The solution is to establish a Binder connection
    pool, that is, to uniformly forward the Binder requests of each business module to a remote Service for execution, thereby avoiding repeated creation of
    Services.
  • Working principle: Each business module creates its own AIDL interface and implements this interface, and then provides its own unique identifier and its corresponding Binder object to the server. The server only needs one Service, and the server provides a queryBinder interface, which will return the corresponding Binder object according to the characteristics of the business module. After different business modules get the required Binder object, they can call the remote method

view interview questions

1. Tell me about the drawing process of View?

  • View's workflow mainly refers to the three major processes of measure, layout, and draw, namely measurement, layout, and drawing. Measure determines the measured width/height of View, and layout determines the final width/height of View and the positions of the four vertices. draw draws the View to the screen

  • The drawing process of View follows the following steps:

1) Draw the background background.draw(canvas)

2) Draw yourself (onDraw)

3) Draw children (dispatchDraw)

4) Draw decorations

2. What is MotionEvent? How many events are included? Under what conditions will it happen?

  • MotionEvent is a series of events generated after the finger touches the screen. Typical event types are as follows:
    1) ACTION_DOWN: the finger just touched the screen

2) ACTION_MOVE: finger moves on the screen

3) ACTION_UP: The moment the finger is released from the screen

4) ACTION_CANCELL: Triggered when the finger keeps pressing and moves from the current control to the outer control

  • Under normal circumstances, a finger touching the screen will trigger a series of click events. Consider the following situations:

1) Release after clicking the screen, event sequence: DOWN→UP

2) Click on the screen to slide for a while and then release, the sequence of events is DOWN→MOVE→…→MOVE→UP

3. Describe the View event delivery and distribution mechanism?

  • The essence of View event distribution is the process of distributing MotionEvent events. That is, when a MotionEvent occurs, the system passes the
    click event to a specific View
  • The order of delivery of click events: Activity (Window) → ViewGroup → View
  • The event distribution process is completed by three methods:

1) dispatchTouchEvent: used to distribute events. If the event can be delivered to the current View, then this method will definitely be called, and the returned result is affected by the onTouchEvent of the current View and the dispatchTouchEvent method of the subordinate View, indicating whether to consume the current event

2) onInterceptTouchEvent: Called inside the above method to intercept the event. This method is only available in ViewGroup, View (not including ViewGroup) is not. Once intercepted, the ViewGroup's onTouchEvent is executed, and the event is processed in the ViewGroup instead of being distributed to the View. And only called once, the returned result indicates whether to intercept the current event

3) onTouchEvent: Called in the dispatchTouchEvent method to process the click event, and the returned result indicates whether to consume the current event

4. How to solve the event conflict of View? Give an example encountered in development?

  • Common event conflicts in development include the sliding conflict between ScrollView and RecyclerView, and the embedded RecyclerView slides in the same direction at the same time
  • Handling rules for sliding conflicts:

1) For sliding conflicts caused by inconsistencies between external sliding and internal sliding directions, it is possible to judge who will intercept the event according to the sliding direction.

2) For sliding conflicts caused by the same external sliding direction and internal sliding direction, you can specify when to let the external View intercept events and when to let the internal View intercept events according to business needs.

3) For the nesting of the above two cases, it is relatively complicated, and a breakthrough point can also be found in the business according to the needs.

  • The implementation method of sliding conflict:

1) External interception method: means that the click event is first intercepted by the parent container, if the parent container needs this event, it will be intercepted, otherwise it will not be intercepted. Specific method: You need to rewrite the onInterceptTouchEvent method of the parent container, and make corresponding interceptions internally.

2) Internal interception method: The parent container does not intercept any events, but passes all events to the child container. If the child container needs this event, it will consume it directly, otherwise it will be processed by the parent container. Specific method: need to cooperate with the requestDisallowInterceptTouchEvent method.

5. What is the difference between scrollTo() and scollBy()?

  • scollBy internally calls scrollTo, which is a relative slide based on the current position; while scrollTo is an absolute slide, so if the scrollTo method is called multiple times with
    the same input parameter, the View will only appear once because the initial position of the View remains unchanged. scrolling effect
  • Both can only slide the View content, not the View itself. Can use Scroller to have excessive sliding effect

6. How does the Scroller realize the elastic sliding of the View?

  • Call the startScroll() method when the MotionEvent.ACTION_UP event is triggered. This method does not perform the actual sliding operation, but records the sliding related amount (sliding distance, sliding time)
  • Then call the invalidate/postInvalidate() method to request the View to redraw, causing the View.draw method to be executed
  • When the View is redrawn, the computeScroll method will be called in the draw method, and the computeScroll will go to the Scroller to obtain the current scrollX and scrollY; then use the scrollTo method to realize sliding; then call the postInvalidate method to perform the second redraw, and the previous process Similarly, such repetitions cause the View to continuously slide in a small range, and multiple small slides form an elastic slide until the entire sliding process is over.

7. What is the difference between invalidate() and postInvalidate()?

Both invalidate() and postInvalidate() are used to refresh the View. The main difference is that invalidate() is called in the main thread. If it is used in a sub-thread, a handler is required;
while postInvalidate() can be called directly in a sub-thread.

8. What is the difference between SurfaceView and View?

  • View needs to refresh the screen on the UI thread, while SurfaceView can refresh the page on the sub-thread
  • View is suitable for active updates, while SurfaceView is suitable for passive updates, such as frequent refreshes. This is because frequent refreshes using View will block the main thread and cause the interface to freeze
  • SurfaceView has implemented a double-buffering mechanism at the bottom layer, but View does not, so SurfaceView is more suitable for pages that require frequent refresh and a large amount of data processing during refresh (such as video playback interface)

9. How to customize View to consider model adaptation?

  • Reasonable use of warp_content, match_parent
  • Use RelativeLayout whenever possible
  • For different models, use different layout files and place them in the corresponding directory, and android will automatically match them.
  • Use density-independent pixel units dp, sp
  • Introduce the percentage layout of android.
  • When cutting a picture, cut a picture with a large resolution and apply it to the layout. It will also have a good display effect on mobile phones with small resolutions.

Replenish:

Because of the space, I can't show more content. All the content has been organized into an interview booklet, including data structure and algorithm, Java foundation, in-depth generics and annotations, concurrent programming, virtual machine principle, reflection class, network programming, Kotlin, Advanced UI, Framework kernel source code, component kernel, performance optimization, open source framework, etc. The QR code below can be obtained directly.

insert image description here

Guess you like

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