Jinsanyin Four, impact factory, you deserve to have a 2019 junior and intermediate mobile terminal recruitment interview summary + solutions

You are currently working on Android.

Android development Agency recruitment interview answer (middle)

Android article: 2019 Junior and intermediate Android development agency recruitment interview answers (next)

Note: because the actual development and reference answers will be different, and afraid of misleading you, so these interview answers or their own to understand! The interviewer will ask questions about the points mentioned in the resume, so don’t memorize the answers. Try to understand them.

Android article

Activity

1. How about the Activity lifecycle?

  • Under normal circumstances, there are only seven common life cycles for an Activity
    • OnCreate () : indicates that the Activity is being created. It is used to initialize the Activity. For example, setContentView is called to load the layout resources of the interface, and data is used to initialize the Activity.
    • OnRestart () : indicates that the Activity is being restarted. Normally, onRestart is invoked when Acitivty becomes visible again.
    • OnStart () : indicates that the Activity is being started. At this point, the Activity is visible but not in the foreground. It is still in the background and cannot interact with users.
    • OnResume () : The Activity gains focus, the Activity is visible in the foreground, and the Activity starts. This is different from onStart.
    • OnPause () : Indicates that the Activity is being stopped. You can store data, stop animation, and so on, but do not take too long, as this will affect the display of the new Activity. OnPause () must be completed before the onResume of the new Activity is executed.
    • OnStop () : indicates that the Activity is about to stop. You can perform some heavyweight reclaiming tasks, such as logging out of the broadcast receiver and closing the network connection.
    • OnDestroy () : indicates that the Activity is about to be destroyed. This is the last callback in the Activity lifecycle.
  • Extension: onCreate and onDestroy are paired throughout the lifecycle, marking the creation and destruction of an Activity, respectively, and can only be called once; OnStart and onStop are paired in terms of whether the Activity is visible, and these two methods can be called multiple times; OnResume and onPause are paired depending on whether the Activity is in the foreground or not, and these two methods can be called multiple times; Apart from this distinction, there is no obvious distinction in practice;

2. What methods will B call when Activity A starts another Activity? What if B is a transparent theme or a DialogActivity?

  • Activity A starts another Activity B with the following callback
    • OnPause () → onCreate() → onStart() → onResume() → onStop();
    • If B is A transparent topic or A DialogActivity, A’s onStop is not called;

What does the onSaveInstanceState() method do? When will it be called?

  • Occurrence conditions: under abnormal circumstances (Activities are killed and recreated when system configuration changes, and low-priority activities are killed due to insufficient resource memory)
    • The system calls onSaveInstanceState to save the current state of the Activity. This method is called before onStop and has no established sequential relationship with onPause.
    • When the Activity is rebuilt, onRestoreInstanceState is called and the onSave(for short) method holds the Bundle objectAt the same time, the participationTo onRestore(for short) and onCreate(), so you can identify activities using these two methodsHas been rebuilt, after onStart;
  • Recommended articles:
    • The official documentation

4. Describe the four startup modes and application scenarios of the Activity.

  • Reference Answer:
    • Standard mode: Each time an Activity is started, a new instance is created, regardless of whether the instance already exists. By default, an Activity in this mode is added to the task stack to which it was started.
    • SingleTop: If a new Activity is already at the top of the stack, the Activity is not recreated, and the onNewIntent method is called back. If the new Activity instance already exists but is not at the top of the stack, the Activity is still recreated.
    • SingleTask stack reuse mode: As long as the Activity exists in A stack, the instance is not recreated by starting the Activity multiple times. The onNewIntent method is called back. This mode starts the Activity A, and the system first looks to see if the desired stack exists. And then put the created instance of A on the stack;
    • SingleInstance: this is an enhanced singleTask mode in which an Activity can only be placed in a singleTask stack with a singleInstance;
  • Recommended articles:
    • The official documentation

5. What Flags are commonly used for activities?

  • Reference Answer:
    • FLAG_ACTIVITY_NEW_TASK: corresponds to the singleTask startup mode, which has the same effect as specifying the startup mode in XML;
    • FLAG_ACTIVITY_SINGLE_TOP: the corresponding singleTop startup mode has the same effect as that specified in XML;
    • FLAG_ACTIVITY_CLEAR_TOP: An Activity with this flag bit. When it starts, all activities above it in the same task stack are removed from the stack. This flag bit is typically used with the singleTask mode, in which the system calls back onNewIntent if an instance of the Activity being started already exists. If the Activity is started in Standard mode, it and other activities on top of it are removed from the stack. A new instance of the Activity is created and added to the stack.
    • FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS: Activities with this flag do not appear in the history Activity list;
  • Recommended articles:
    • The official documentation

6. Describe the relationship between an Activity and a window or view.

  • Reference Answer:
    • When an Activity is created, it calls attach() to initialize a PhoneWindow(inherited from Window), and each Activity contains a unique PhoneWindow
    • The Activity sets the View to the PhoneWindow by setContentView which is actually called getWindow(). SetContentView, PhoneWindow uses addView, removeView, and updateViewLayout to manage views. WindowManager is an interface. The final implementation is Windows ManagerImpl
  • extension
    • WindowManagerFor eachWindowcreateSurfaceObject, and then the application can go through thisSurfaceTo draw whatever it wants to draw. And forWindowManagerIn general, this is just a rectangular area
      • A Surface is simply an object that holds a matrix of pixels that form part of the image displayed on the screen. Each Window we see displayed (including dialog boxes, full-screen activities, status bars, etc.) has its own Surface drawn. The final display may have the problem of blocking between Windows. In this case, the final display is rendered by SurfaceFlinger object, so that they are displayed in the correct Z-order. Surface has one or more caches (usually two), and is refreshed by a double cache so that new caches can be added as you draw.
    • A View is the UI element inside the Window that you interact with. The Window only attaches a View Tree. When the Window needs to be redrawn (e.g. when the View calls invalidate), the Surface becomes locked and the Canvas object is returned. Now the View takes the Canvas object and draws itself. When all views are drawn, Surface unlocks (UNLOCK) and posts to draw cache for drawing. Surface Flinger organizes each Window to display the entire screen
  • Recommended articles:
    • An article is enough to understand activities, views, and Windows

7. Activity life cycle changes for vertical screen switching?

  • Reference Answer:
    • With Android :configChanges not configured for the Activity, the current Activity is destroyed when the screen is cut, and the life cycle of the call is reloaded, once for landscape and twice for portrait. OnPause () – > onStop () – > onDestory () – > onCreate () – > onStart () and onResume ()
    • Android :configChanges=”orientation“, after the model test
      • In Android5.1, i.e., API 23 level, the screen cutting will still be re-called for each life cycle, cutting landscape and portrait will only be performed once
      • On Android9, or API 28, the screen cut does not re-invoke the various lifecycles. only the onConfigurationChanged method is executed
      • After the official check“The words are as follows
        • If your application is facing Android 3.2 at API level 13 or higher (as stated by the minSdkVersion and targetSdkVersion attributes), you should also declare the “screenSize” configuration, because when the device switches between landscape and portrait, The configuration also changes. This configuration change does not restart the Activity even if it is running on Android 3.2 or later devices
    • Set up the Activity of the android: configChanges = “orientation” | keyboardHidden | screenSize “, through model test, cut the screen each life cycle will not call again, Only the onConfigurationChanged method is executed;
  • Recommended articles:
    • Android toggles between horizontal and vertical screens to load different layouts

8. How do I start an Activity for another application?

  • Reference Answer:
    • IntentFilter matches the target Activity with an implicit Intent that guarantees access. The principle is:
      • An intent matches only the action, category, and data in the intent-filter of an Activity.
      • An Activity can have multiple intent-filters. If an intent successfully matches any set of intent-filters, the Activity can be started.
  • Recommended articles:
    • Specific matching rules for action, category, and Data

How does the Activity start? (key)

  • Reference Answer:
    • The first is whether the current system has the Application process. If not, the APP startup process needs to be handled. After creating the process and binding the Application steps, you actually start the method to start the Activity. The startActivity() method ends up calling startActivityForResult().
    • In startActivityForResult(), the actual implementation of the Activity is started in the execStartActivivity() method of the Instrumentation.
    • CheckStartActivityResult () is used in execStartActivity() to check whether it is registered in the manifest and throw an exception if it is not. Otherwise, the task of starting the Activity is delegated to ActivityThread’s inner class ApplicationThread, which implements the IApplicationThread interface. This class completely handles the lifecycle callback methods for activities such as onCreate() and onStart().
    • In the ApplicationThread class, there is a method called scheduleLaunchActivity() that constructs an Activity entry and sends a message to a predefined Handler. This Handler is responsible for making different Activity launches depending on the LAUNCH_ACTIVITY type. There is a method called ᯿ handleLaunchActivity().
    • In handleLaunchActivity(), the start Activity is handed over to the performLaunchActivity() method. In the performLaunchActivity() method, the launch parameters of the target Activity are first resolved from the Intent, Then use a ClassLoader to load the target Activity class by class name and instantiate an object with newInstance(). Once created, the onCreate() method of the Activity is called, and the Activity is successfully started.
  • Recommended articles:
    • The Activity startup process of Android’s four component startup mechanisms

Fragment

1. How about the Fragment lifecycle?

  • Reference Answer:
    • The methods involved in the Fragment lifecycle from creation to destruction are as follows: OnAttach () – > onCreate () – > OnCreateView () – > onActivityCreated () – > onStart () and onResume () – > onPause () – > onStop () – > onDestroyView () – > onDestroy () – > onDetach (), There are a number of methods with the same name and function as Activity, but the different methods are:
      • OnAttach () : called when the Fragment is associated with the Activity;
      • 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 the Fragment and Activity are unassociated;
  • Recommended articles:
    • Fragment advantages of Android

2, what is the difference between Activity and Fragment?

  • Reference Answer:
    • Similarities: Both can contain layouts and have their own life cycle
    • Difference:
      • Fragment has 4 more callback cycles than Activity, and is more flexible in control operation.
      • Fragment can be written directly to an XML file or added dynamically to an Activity.
      • You can use show()/hide() or replace() to switch the Fragment at any time, and there will be no obvious effect when switching. The user experience will be better. Although activities can also be switched, but switching between activities will have obvious page-turning or other effects, in a small part of the content of the switch to the user’s feeling is not very good;

3, The difference between add and replace in Fragment

  • Reference Answer:
    • Add does not reinitialize the fragment, replace does every time. So if you retrieve data during the Fragment life cycle, using replace will retrieve data repeatedly;
    • When the same fragment is added, replace does not change, and Add reports an IllegalStateException.
    • Replace removes all fragments with the same ID and then adds the current fragment. Add overwrites the previous fragment. So add is usually accompanied by hide() and show() to avoid overlapping layouts;
    • With Add, if your app is in the background or otherwise destroyed by the system, the fragment referenced in hide() will be destroyed when you open it again, so the layout overlap bug will still occur. You can use replace or add with a tag argument.

The difference between 4, getFragmentManager, getSupportFragmentManager, getChildFragmentManager?

  • Reference Answer:
    • GetFragmentManager () gets the parent container manager of the fragment. GetChildFragmentManager () gets the parent container manager of the fragment. Then you need to use getChildFragmentManager();
    • FragmentManager() : FragmentManager() : FragmentManager() : FragmentManager() : FragmentManager() : FragmentManager() And 3.0 the following is you need to call getSupportFragmentManager () to obtain indirect;

5, the difference between the FragmentPagerAdapter and FragmentStatePagerAdapter and usage scenarios

  • Reference Answer:
    • Similarities: Both inherit PagerAdapter
    • Difference: Each Fragment of the FragmentPagerAdapter persists in the FragmentManager and is not destroyed as long as the user can return to the page. Therefore, it is suitable for those pages whose data is relatively static and the number of fragments is relatively small. FragmentStatePagerAdapter keep only the current page, when the page is not visible, the fragments will be eliminated, release the resources. Therefore, it is suitable for those cases with large dynamic data, large memory occupation and many fragments.

Service

1. How about the Service lifecycle?

  • The life cycle of a Service involves six methods
    • OnCreate () : If the service has not been created, the onCreate() callback is executed after startService() is called; If the service is already running, calling startService() does not execute the onCreate() method. That is, onCreate() is called only when a service is created for the first time, and onCreate() is not called repeatedly when startService() is executed multiple times. This method is good for doing some initialization;
    • OnStartComand () : called when the service starts. This method is good for doing some data loading, such as creating a thread to download data or play music;
    • OnBind () : called when the service is bound;
    • OnUnBind () : called when the service is unbound;
    • OnDestroy () : called when the service stops;
  • Recommended articles:
    • Android component series —- In-depth analysis of Android Service components

2. What are the two startup modes of Service? What’s the difference?

  • Reference answer: Two startup modes of Service
    • StartService () : By calling startService in this way, onCreate() is called only once, and multiple calls to startSercie will execute the onStartCommand() and onStart() methods multiple times. If the stopService() or stopSelf() method is not called externally, the service keeps running.
    • bindService(): If the service is priorHaven’t create, the system callback sequence is onCreate()→onBind(). If you call the bindService() method before the serviceAlready boundCalling the bindService() method multiple times does not create services and bindings multiple times. If the caller wants to bind to the serviceRemove the binding, you can call the unbindService() method, onUnbind()→onDestroy();
  • Recommended articles:
    • The two startup modes of Android Service are explained in detail

3. How to ensure that Service is not killed?

  • Reference Answer:
    • In onStartCommand, START_STICKY or START_REDELIVER_INTENT is returned
      • START_STICKY: If START_STICKY is returned, the Android system will set the Service to the started state (running state) after the process running the Service is forcibly killed. However, the Intent object passed in by the onStartCommand method is no longer saved
      • START_NOT_STICKY: If START_NOT_STICKY is returned, the Service will not be created after the process running on it is forcibly killed by the Android system
      • START_REDELIVER_INTENT: If START_REDELIVER_INTENT is returned, the return is similar to START_STICKY, The difference is that the Intent that was last passed into the onStartCommand method is retained and passed back into the onStartCommand method of the newly created Service
    • Android :priority = “1000” android:priority = “1000” Android :priority = “1000” Androidmanifest.xml Also applicable to broadcasting;
    • Restart the Service in onDestroy. When the Service goes to onDestroy(), it sends a custom broadcast. When it receives a broadcast, it restarts the Service.
    • Improving the priority of Service processes The priority of Service processes changes from high to low: Foreground process, visible process, Service process, background process, empty process Can use startForeground to foreground state, so that the probability of Service being killed is lower when the memory is low.
    • The system broadcasts the Service status
    • Install APK into/System /app to make it a system level application
  • Note: None of the above mechanisms can guarantee that a Service will not be killed unless the system is whitelisted, living and dying with the system

4. Can Service start time-consuming operation? How to do?

  • Reference Answer:
    • A Service does not run in child threads by default, nor does it run in a separate process; it also runs in the main thread (UI thread). In other words, do not perform time-consuming operations in a Service. Unless a child thread is opened manually, the main thread may be blocked (ANR).

5. Which system services have you used?

  • Reference Answer:

Do you know ActivityManagerService? What role to play

  • ActivityManagerService is the most core service in Android. It is responsible for starting, switching, and scheduling the four major components of the system, and managing and scheduling application processes. Its responsibilities are similar to those of the process management and scheduling module in the operating system.
  • Recommended articles:
    • ActivityManagerService analysis — AMS startup process

Broadcast Receiver

1. How many forms of broadcasting are there? What are the features?

  • Reference Answer:
    • Normal broadcast: an intent broadcast defined by the developer (most commonly) that is received by all broadcast receivers at approximately the same time, in a random order.
    • Orderly broadcast: send out radio is broadcast receiver according to the order received, the same time there will be only one radio receiver can receive the broadcast message, when after the execution of logic of the radio receiver, radio will continue to pass, and a higher priority (priority) radio receiver would receive broadcast messages first. An ordered broadcast can be intercepted by a receiver so that subsequent receivers cannot receive it;
    • Local broadcast: Only local applications can send and receive broadcasts, which is more secure and efficient. However, only dynamic registration can be used.
    • Sticky broadcast: this kind of broadcast will linger, when a matching receiver is registered, the receiver will receive this broadcast;
  • Recommended articles:
    • BroadcastReceiver is the most comprehensive overview of Android

2. Two ways of broadcasting registration?

  • Reference Answer:

3. Do you know the principle of broadcast sending and receiving? (Binder mechanism, AMS)

  • Reference Answer:
  • Recommended articles:
    • The underlying implementation principles of broadcasting

ContentProvider

1. What do you know about ContentProvider?

  • Reference Answer:
    • As one of the four components, ContentProvider is responsible for storing and sharing data. Unlike file storage, SharedPreferences storage, or SQLite database storage, which stores data that can only be used by the application, the former allows different applications to share data and choose which part of the data to share. In order to ensure that the privacy of the program data will not have the risk of leakage.
  • Recommended articles:
    • Android: All about ContentProvider knowledge here!

2. Permission management of ContentProvider?

  • Reference Answer:
    • Reading and writing separation
    • Permission control – table level precision
    • URL control

ContentProvider (ContentObserver) ContentResolver (ContentObserver)

  • Reference Answer:
    • ContentProvider: Manages data and provides operations of adding, deleting, modifying, and querying data. Data sources can be databases, files, XML, and networks. ContentProvider provides a unified interface for accessing these data and can be used to share data between processes.
    • ContentResolver: A ContentResolver can manipulate data in different ContentProviders for different URIs, and external processes can interact with the ContentProvider through the ContentResolver.
    • ContentObserver: Watches data changes in ContentProvider and notifies the outside world of the changes.

Data is stored

1. Describe how Android data persistence works.

  • Reference answer: There are several common ways to implement persistent data storage on Android platform:
    • SharedPreferences storage: A lightweight data storage method, which is essentially key-value pair data stored based on XML files. It is usually used to store some simple configuration information (such as various configuration information of an application program).
    • SQLite database storage: A lightweight embedded database engine that is very fast and consumes few resources. It is commonly used to store a large number of complex relational data.
    • ContentProvider: one of the four components used for data storage and sharing. It not only enables different applications to share data, but also selects which part of the data to share, which ensures that the private data in the program will not be exposed.
    • File storage: Write and read files in the same way as Java I/O programs;
    • Network storage: Data is stored on a remote server. The data of user operations can be synchronized to the server.

2, The application scenario of SharedPreferences What to note?

  • Reference Answer:
    • SharedPreferences SharedPreferences is a lightweight data storage method that essentially stores key-value pairs based on XML files. It is usually used to store simple configuration information, such as INT, String, Boolean, float, and LONG.
    • Matters needing attention:
      • Do not store large, complex data, which can cause memory GC, block the main thread and cause the page to stall and generate ANR
      • Do not operate Sp in multi-process mode
      • Don’t edit and apply more than once. Try to batch change a submission
      • Apply and commit are recommended
  • Recommended articles:
    • The most comprehensive, clear SharedPreferences parsing ever
    • Use SharedPreferences in multiple processes and precautions

3. What is the difference between apply and COMMIT for SharedPrefrences?

  • Reference Answer:
    • Apply returns no value and commit returns Boolean indicating whether the change was committed successfully.
    • Apply commits modified data atoms to memory and then asynchronously commits them to hardware disks, whereas commit synchronously commits to hardware disks. Therefore, when multiple concurrent commits are committed, they wait for the ongoing commit to be saved to disk before operating, thus reducing efficiency. However, apply is only atomic commits to content, and subsequent functions that call Apply will directly overwrite the previous memory data, thus improving efficiency to a certain extent.
    • The Apply method does not prompt for any failures. Since sharedPreference is a single instance in a process, concurrency conflicts generally do not occur. If you do not care about the result of the submission, it is recommended to use Apply. Of course, if you need to ensure the successful submission and subsequent operations, you still need to use COMMIT.

4. Know about transactions in SQLite? How is it done

  • Reference Answer:
    • When SQLite performs CRDU operations, the transaction is enabled by default, and the SQL statement is translated into the corresponding SQLiteStatement and the corresponding CRUD method is called. At this time, the whole operation is still carried out on the temporary file rollback Journal, and the DB database will be updated only when the operation is successfully completed. Otherwise it will be rolled back;

5. Is there a good way to use SQLite to do batch operations?

  • Reference Answer:
    • Start a transaction with the beginTransaction method of SQLiteDatabase, convert the batch operation SQL statement to SQLiteStatement and execute the batch operation, and then endTransaction()

6. How do I delete individual columns from a table in SQLite

  • Reference Answer:
    • SQLite database only allows you to add fields, but not modify or delete table fields. You can only create a new table to retain the original fields and delete the original table

7. What optimizations will occur when using SQLite?

  • Reference Answer:
    • Use transactions to do batch operations
    • Close the Cursor in time to avoid memory leaks
    • Asynchronization of time-consuming operations: Database operations are local I/O time-consuming operations and are recommended to be processed in asynchronous threads
    • ContentValues’ capacity adjustment: ContentValues uses HashMap internally to store key-value data. The initial capacity of ContentValues is 8, which will be doubled when expanded. Therefore, it is recommended to estimate the content filled in ContentValues and set a reasonable initial capacity to reduce unnecessary internal expansion operations
    • Using indexes to speed up search: Indexes are recommended for those with a large number of query operations and high service requirements

IPC

1. The relationship between processes and threads in Android? The difference between them?

  • Reference Answer:
    • Thread is the smallest unit of CPU scheduling, and thread is a limited system resource
    • A process is typically a unit of execution, a program or an application on a PC or mobile device
    • In general, an App has at least one process, a process of at least one thread (including relationship with included), popular terms, is that there is a process in App this factory, the inside of the thread is production line, but the main thread (main production) is only one, but the child thread can have multiple (production line)
    • A process has its own independent address space, which is shared by threads in the process and can execute concurrently
  • Recommended articles:
    • Android Developer official documentation – Processes and Threads

2. How to enable multiple processes? Can N processes be enabled for an application?

  • Reference Answer:
    • Android: Process Enables multi-process mode
    • N processes can be started if memory permits
  • Recommended explanation:
    • How do I enable multiple processes? Can N processes be enabled for an application?

3. Why is IPC needed? Possible problems with multi-process communication?

  • Reference Answer:
    • All the four major components (Activity, Service, Receiver, and ContentProvider) running on different processes fail to share data. This is because Android allocates a separate VIRTUAL machine for each application. Different virtual machines have different address Spaces for memory allocation. This results in multiple copies of objects of the same class being accessed in different virtual machines. Common examples (more memory by enabling multiple processes, sharing data between two or more applications, wechat family bucket)
    • In general, the use of multi-process communication will cause the following problems
      • Static member mode and singleton mode completely fail: independent VM
      • The thread synchronization mechanism is fully effective: independent virtual machines
      • The reliability of SharedPreferences deteriorates: Sp does not support concurrent read and write of two processes, which may lead to data loss
      • Applications are created multiple times: The Android system allocates a separate VIRTUAL machine when creating a new process, so this process is actually the process of starting an Application, and new applications will be created naturally
  • Recommended articles:
    • Android Developer official documentation – Processes and Threads

4. Advantages and disadvantages of IPC and various methods in Android, why Binder?

  • Reference Answer:

    How is Binder better than traditional IPC mechanisms on Linux, such as System V and Socket?

    • High transmission efficiency and operability: The transmission efficiency is mainly affected by the number of memory copies. The smaller the number of memory copies, the higher the transmission rate. Analysis from the perspective of Android process architecture: For message queues, sockets and pipes, data is first copied from the sender’s cache to the cache created by the kernel, and then copied from the kernel cache to the receiver’s cache, twice in total, as shown in the figure:

      With Binder, data is copied from the sender’s cache to the kernel’s cache, while the receiver’s cache and the kernel’s cache are mapped to the same physical address, saving a data copy process, as shown in the figure below:

      Due to the complexity of shared memory operations, binders provide the best transport efficiency.

    • Convenient implementation of C/S architecture: All Linux IPC methods are not based on C/S architecture except Socket, which is mainly used for communication between networks and has low transmission efficiency. Binder based on C/S architecture, the Server and Client are relatively independent, providing high stability.
    • High security: The receiver of traditional Linux IPC cannot obtain the reliable UID/PID of the process of the other party, so it cannot identify the other party. The Binder mechanism assigns a UID/PID to each process and checks its validity when it communicates with the Binder.
  • Recommended articles:
    • Why did Android adopt Binder as an IPC mechanism?

5. What are the functions and principles of Binder mechanisms?

  • Reference Answer:
    • Linux divides a process into two groupsThe user spaceandThe kernel space. Data in user space cannot be shared between processes, while data in kernel space can be shared. To ensure security and independence, one process cannot directly operate or access another process. In other words, Android processes are independent and isolated from each other, which requires cross-process data communication
  • A complete Binder IPC communication process usually looks like this:
    • First, the Binder driver creates a data receive cache in kernel space.
    • Then, a kernel cache is created in the kernel space, and the mapping relationship between the kernel cache and the kernel data receiving cache, as well as the mapping relationship between the kernel data receiving cache and the user space address of the receiving process is established.
    • The sender process uses the system call copyfromuser() to copy the data to the kernel cache in the kernel. Since there is memory mapping between the kernel cache and the user space of the receiving process, the data is sent to the user space of the receiving process, thus completing an inter-process communication.

6. The role of ServiceManager in Binder framework?

  • Reference Answer:
    • Binder frameworkIt is based on C/S architecture. It consists of a series of components, including Client, Server, ServiceManager, and Binder drivers. Client, Server, and ServiceManager run in user space, and Binder drivers run in kernel space
      • Server&Client: Server&Client. Client-server communication is performed over infrastructure provided by Binder drivers and Service Manager.
      • A ServiceManager (like a DNS Server) ServiceManager translates Binder names into references to the Binder names in clients so that clients can obtain references to Binder entities in servers using Binder names.
      • Binder drive(like router) : responsible for low-level support of binder communication between processes, including establishment, transfer, count management and data transfer and interaction.

        Binder: Cross-process Communication with Android

7. Why do Bundle delivery objects need to be serialized? The difference between Serialzable and Parcelable?

  • Reference Answer:
    • Because the Bundle only supports basic data types when passing data, it needs to serialize to a stored or transportable intrinsic state (byte stream) when passing objects. Serialized objects can be transferred between the network, IPC (such as an Activity that starts another process, Service, and Reciver), or stored locally.
    • There are two ways to implement serialization: implement the Serializable/Parcelable interface. The differences are shown as follows:

8. Tell me about AIDL? How does it work? How to optimize AIDL for multiple modules?

  • Reference Answer:
    • Android Interface Definition Language (AIDL) If you want to call a method on an object in another process, you can use AIDL to generate serializable parameters. AIDL generates a proxy class for a server object through which the client implements indirect calls to the methods on the server object.
    • The essence of AIDL is that the system provides a set of tools to implement Binder quickly. Key classes and methods:
      • AIDL interface: Inherits IInterface.
      • Stub class: Implementation class for Binder, through which servers provide services.
      • Proxy class: the server’s local Proxy through which the client invokes the server’s methods.
      • AsInterface () : a client call that converts Binder objects returned by the server into AIDL interface type objects required by the client. If the client and server are in the same process, the Stub object itself is directly returned. Otherwise, the encapsulated stub. proxy object is returned
      • AsBinder () : Returns the Binder object of the Proxy based on the current invocation.
      • OnTransact () : When a client makes a cross-process request in the Binder thread pool on the server side, the remote request is processed by this method after being wrapped by the underlying system.
      • Transact () : Runs on the client and suspends the current thread when the client initiates a remote request. OnTransact () is then called on the server side and the current thread does not resume execution until the remote request returns.
    • When you have multiple business modules that require AIDL for IPC, you need to create a specific AIDL file for each module, and there are many services. It is inevitable that there will be serious system resource consumption and excessive application heavyweight problems. The solution is to pool Binder connections, which centrally forward Binder requests from each business module to a remote Service to avoid duplicate Service creation.
      • How it works: Each business module creates and implements its own AIDL interface, and then provides its own unique identity and corresponding Binder objects to the server. The server only needs one Service. The server provides a queryBinder interface, which will return corresponding Binder objects according to the characteristics of business modules. After different business modules get the required Binder objects, they can call remote methods

View

1, talk about the drawing process of View?

  • Reference Answer:
    • The workflow of View mainly refers to measure, layout and draw, namely measurement, layout and drawing. Measure determines the measuring width/height of View, Layout determines the final width/height of View and the position of four vertices, and DRAW draws the View on the screen
    • The process of drawing a View follows the following steps:
      • Draw background.draw(canvas)
      • OnDraw yourself
      • Draw Children (dispatchDraw)
      • Draw decorative(onDrawScollBars)
  • Recommended articles:
    • The official documentation
    • Android View drawing process
    • Android application layer View drawing process and source code analysis

What is a MotionEvent? How many events are involved? Under what conditions does it occur?

  • Reference Answer:
    • A MotionEvent is a series of events that occur when a finger touches the screen. Typical event types are as follows:
      • ACTION_DOWN: the finger just touches the screen
      • ACTION_MOVE: Move your finger on the screen
      • ACTION_UP: The moment your finger is released from the screen
      • ACTION_CANCELL: Triggered when the finger holds down and moves from the current control to the outer control
    • Normally, a single finger touch on the screen triggers a series of clicks. Consider the following:
      • Click the screen and release it. The sequence of events: DOWN→UP
      • Click the screen to slide for a while and then release it. The event sequence is DOWN→MOVE→….. – MOVE – UP

3. Describe the View event distribution mechanism.

  • Reference Answer:
    • View event distribution is essentially the process of MotionEvent distribution. When a MotionEvent occurs, the system passes the click event to a specific View
    • Click the event delivery order: Activity (Window) →ViewGroup→ View
    • The event distribution process is accomplished in three ways:
      • DispatchTouchEvent: Used for event distribution. This method must be called if the event can be passed to the current View, and the return result is affected by the current View’s onTouchEvent and the lower View’s dispatchTouchEvent methods, indicating whether the current event is consumed
      • OnInterceptTouchEvent: Called inside the above method to intercept the event. This method is only available in viewgroups, not views (excluding viewgroups). Once intercepted, onTouchEvent of the ViewGroup is executed and the event is processed in the ViewGroup rather than subsequently distributed to the View. It is called only once and returns a result indicating whether the current event is intercepted
      • OnTouchEvent: Called in the dispatchTouchEvent method to handle the click event and return a result indicating whether the current event is consumed

4, How to resolve the View event conflict? What is an example from development?

  • Reference Answer:
    • Common development events conflict between ScrollView and RecyclerView sliding conflict, RecyclerView embedded sliding in the same direction at the same time
    • Handling rules of sliding conflicts:
      • In the case of slide collisions due to inconsistent external and internal slide directions, it is possible to determine who intercepts the event based on the direction of the slide.
      • For sliding conflicts caused by the same external and internal sliding directions, depending on business requirements, you can specify when to let the external View intercept the event and when to let the internal View intercept the event.
      • For the nesting of the above two cases, relatively complex, according to the same needs to find a breakthrough in the business.
    • Implementation method of sliding conflict:
      • External interception: the click event is first intercepted by the parent container. If the parent container needs the event, it will be blocked. Otherwise, it will not be blocked. You need to override the onInterceptTouchEvent method of the parent container and intercept it internally.
      • Internal interception: The parent does not intercept any events, but passes all events to the child. If the child needs the event, the child consumes it; otherwise, the parent processes it. Specific methods: need to match the requestDisallowInterceptTouchEvent method.

ScrollTo () and scollBy()?

  • Reference Answer:
    • ScollBy internally calls scrollTo, which is a relative slide based on the current position; ScrollTo is an absolute slide, so if you call scrollTo multiple times with the same input parameter, the View will only scroll once because its initial position is the same
    • Both can only slide the contents of the View, not the View itself. The Scroller can be used for excessive sliding
  • Recommended articles:
    • View sliding principle and implementation

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

  • Reference Answer:
    • The startScroll() method is called when the motionEvent.action_UP event is triggered. This method does not perform the actual sliding operation, but records the sliding relative quantity (sliding distance, sliding time).
    • Then call invalidate/postInvalidate () method, requests the View re-paint, lead to the draw method is executed
    • ComputeScroll will be called in the Draw method when the View is redrawn, and computeScroll will fetch the current scrollX and scrollY from Scroller. Then through the scrollTo method to achieve sliding; Then, the postInvalidate method is called for the second redrawing. The same as the previous process, such a repetition causes the View to slide continuously in small amplitude, and many small amplitude slides constitute an elastic slide until the whole slide is finished

7, How does invalidate() differ from postInvalidate()?

  • Reference Answer:
    • Invalidate() and postInvalidate() are both used to refresh views. The main difference is that invalidate() is called in the main thread, and if used in child threads, a handler is required. PostInvalidate () can be called directly from a child thread.

8, SurfaceView and View difference?

  • Reference Answer:
    • The View needs to refresh the screen in the UI thread, while the SurfaceView can refresh the page in the child thread
    • The View is good for active updates, while the SurfaceView is good for passive updates, such as frequent refreshes, because frequent refreshes with the View will block the main thread and cause the interface to get stuck
    • The SurfaceView has dual buffering at the bottom, while the View does not. Therefore, the SurfaceView is more suitable for pages that require frequent refresh and heavy data processing (such as video playback interface).

9, how to consider the model adaptation of custom View?

  • Reference Answer:
    • Fair use of warp_content, match_parent
    • Use RelativeLayout whenever possible
    • For different models, use different layout files in the corresponding directory, Android will automatically match.
    • Use dot 9 images whenever possible.
    • Use density-independent pixel units dp, sp
    • Introduce the percentage layout for Android.
    • When cutting images, cut large resolution images and apply them to the layout. It also works well on small resolution phones.

You are currently working on Android.

Android development Agency recruitment interview answer (middle)

Android article: 2019 Junior and intermediate Android development agency recruitment interview answers (next)