current position:Home>Summary of common knowledge points of Android interview in 2020, HashMap traversal

Summary of common knowledge points of Android interview in 2020, HashMap traversal

2022-02-04 16:37:58 m0_ sixty-four million three hundred and fourteen thousand four

BroadcastReceiver:

  • General broadcasting 、

  • System broadcast : Some built-in broadcasts in the system , For example, monitoring network changes 、 Turn on the camera and so on

  • Ordered broadcasting :

  • The recipients receive... In sequence according to the pre-declared priority Broadcast;

  • Data can be stored in the result object , To the next recipient ;

  • Can be terminated by a certain receiver .

  • Local radio (APP Inside )

ContentProvider:


Android process ( Grade )

  1. foreground process Front end process

The front-end process is the process currently displayed on the screen to interact with users

for instance :

  1. Top level interactive activity( Has been carried out onResume);
  2. There is one Service, And bind to the... That the user is interacting with activity;
  3. stay Service In the call startForground function ;
  4. Being implemented onReceive Functional BroadCastReceiver
  5. visible process See the process

There are no front desk components , But it can still affect what users see on the screen .
such as :

  • If one activity After a dialog is run, it is still visible ;
  • When the input method pops up .
  1. Service process Service process
    The service process is not directly visible to the user
    For example, playing in the background mp3 Or download something from the Internet

  2. background process Background processes
    such as :Activity Yes onStop

  3. empty process Empty process


Data persistence

SQLight:

  • SQLite It's a lightweight database , Support basic SQL grammar
  • SQLiteDatabase Class , Encapsulates some operations of the database api
    1. context.openOrCreateDatabase() Method creation SQLiteDatabase example
    2. SQLiteDatabase The instance insert() Method insert data
    3. call query() Method query data
    4. call execSQL() Method execution SQL sentence

SharedPreference:

  • It's a lightweight way to store data , Store data in the right way .
  • Its essence is a xml file , Generally located /data/data/ Package name /shared_prefs/ Under the table of contents .
  • Due to the presence of... In memory sharedPreference File cache , So in a multi process environment , The system is unreliable in its reading and writing . Therefore, it is not recommended to use in IPC in

ContentProvider:

  • Android A data storage method that can be shared between different applications in the system . For example, audio , video , Pictures and contacts , Generally, it can be stored in this way
  • Every Content Provider Will provide a public URI, The application passes this URI To operate on data .
  • Content Provider Naturally supports cross process access , Therefore, it can be used for IPC

Android How do applications share data ?

File,Sqlite,Content Provider,BroadCast Receiver,Intent, Same Application Internally, you can also share data through static variables .


webView

load

  1. Increase the priority of rendering

webSettings.setRenderPriority(RenderPriority.HIGH);

  1. Put the image load at the end to load the rendering

webSettings.setBlockNetworkImage(true);

  1. Using hardware acceleration , This function is available in Android 3.0 (API level 11) To join in .
    Hardware acceleration can be turned on or off at the following four levels :Application、Activity、Window、View
    such as , stay AndroidManifest.xml Add android:hardwareAccelerated attribute ; close view Hardware acceleration myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

  2. Open the cache
    Set up websetting

js and java Object interaction

  1. obtain webview The control of websetting

  2. Set up websetting.setJavascriptEnabled( true )

  3. Expose an object to JavaScript:webview.addJavascriptInterface. This object contains JS Method called , These methods use @JavascriptInterface modification

  4. JS Through these methods and Android Interaction

prevent OOM

  1. Dynamically place... In your code webview Set to layout , Instead of writing directly to xml In file ;
  2. stay Activity Of onDestory Medium destruction webview

Thread related

Linux Thread basis

  • The difference between thread and process
  • Thread synchronization
  • Linux Thread communication mode

ANR

  • what
  • Activity 5s No response within ,BroadcastReceiver 10s No response within
  • /data/anr/traces.txt The document records ANR Information about
  • why
  • how

Time consuming tasks or inter thread communication

  • AsyncTask

  • In essence, it is right to ThreadPool and Handler An encapsulation of

  • The default is serial execution tasks , You can call executeOnExecutors() Method executes tasks in parallel

  • Handler

  • IntentService

Handler

  • Handler + MessageQueue + Looper

MessageQueue It's essentially a Single chain list , No Queue. use FIFO Mode management ,enqueueMessage() The method is to insert the message into a queue ,next() Method is an infinite loop method . If there's news , Take out , without , Just block .

  • HandlerThread

It is essentially an inheritance Thread Thread class of .
By creating a HandlerThread obtain looper object , Pass to Handler object , Perform asynchronous tasks . stay HandlerThread Pass through **Looper.prepare() To create a message queue , And pass Looper.loop()** To start the message loop . establish HandlerThread You have to call start() Method , To call getLooper() obtain Looper object .

HandlerThread Encapsulates the Looper object , So that we don't have to care about Looper Details of the opening and release of . If not HandlerThread Words , It needs to be called manually Looper.prepare() and Looper.loop() These methods .

Android Analysis of electronic version of refined interview questions

IntentService

  • principle :IntentService It's a abstract class , Encapsulates the HandlerThread and Handler, Responsible for handling time-consuming tasks . When the task is completed, it will stop automatically . stay onCreate() Method opens a HandlerThread Threads , After through HandlerThread Of Looper I've initialized one Handler, Responsible for handling time-consuming operations . adopt startService() Method start up , stay handler Call in Abstract method onHandleIntent(), This method is called automatically after execution stopself() Method stop

  • override onHandleIntent() Method

  • advantage : On the one hand, you don't need to create threads yourself , On the other hand, there is no need to consider when to close the Service

OOM

  • what
    OOM and Memory leak The difference between

  • how

  • Static variables hold Activity or Context object

  • Instances of non static inner classes ( By default, it holds references to external classes )

  • Resource not closed :file、stream、bitmap etc.

  • Handler cause OOM

  • reason : Use **( anonymous ) Inner class ** Instantiation handler, Default holding context quote

  • avoid : Static inner class 、Activity stay onDestroy When , Empty handler Unhandled message

  • WebView cause OOM


View relevant

Trilogy

Three core steps :Measure、Layout、Draw

Touch Distribution mechanism

important

Slide conflict

sketch Activity、Window、WindowManager、View、ViewRootImpl Role and relationship between

  • Activity Not responsible for view control , It is to hand over to Window. This Window It's essentially a PhoneWindow, By windowmanager management .

  • Window There is decorview,decorview Is the bottom layer of the current view View, yes setContentView Set View The father of View
    View Is the base class for all controls .

  • ViewRoot Corresponding ViewRootImpl, It's a connection WindowManager and DecorView The link between . The three processes are drawn in ViewRootImpl Done in : from ViewRootImpl Medium performTraversals Start , There are three ways performMeasure, performLayout, prformDraw They correspond to each other measure,layout,draw Three processes , Complete the top View The draw .

  • In the father View Of Measure In the process , Can call the child View Of Measure The process , So again and again , Complete the whole View Tree traversal . Empathy , stay Layout and Draw It's the same with China .

RecyclerView

  • advantage :

  • Encapsulates the ViewHolder

  • And ListView comparison , Less coupling 、 More flexible : according to viewType Set up different layouts

  • Set up LayoutManager, Realization ListView The function and GridView The function of ( Support LinearLayoutManager and GridLayoutManager)

  • Support local refresh :notifyItemChanged() Method (Listview With BaseAdapter Only notifyDataSetChanged() Method )

  • shortcoming :

  • Use more complex

  • No, onItemClickListener()、setOnItemLongClickListener() Method , Only OnItemTouchListener() Method

  • RecyclerView.Adapter

  • onCreateViewHolder() Method : Produce a ViewHolder object , This object encapsulates view

  • onBindViewHolder() Method : Based on the incoming ViewHolder object , Display the data

  • getItemViewType() Method : According to the circumstances , Return to a different viewType, It is convenient for subsequent display of different layouts and business processing


IPC

Linux in IPC The way : name pipes 、 Semaphore 、 Shared memory

Basics

  • The way to start multiple processes : Give the four components in Menifest In file , add to process attribute , Specify the process name
  • Android Assign one to each process Stand alone virtual machine , Different Application And address space .
  • Different processes have different copies of objects accessing the same class . Therefore, static members and singleton mode fail 、 Thread synchronization failed 、sharedPreference Reduced reliability .

serialize

  • Serializable Interface :Java Serialization interface for , Easy to use , But it costs a lot , Serialization and deserialization require a lot of IO operation

  • Parcelable Interface : yes Android How to serialize , Complex use , But it's efficient .

  • Objects cannot be transferred directly across processes . Cross process transfer of objects , Its essence is the process of serialization and deserialization

Mechanism :Bundle、 File sharing 、Co

《Android Summary of learning notes + Latest mobile architecture video + Big Android interview questions + Project actual combat source code handout 》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 Full content open source sharing

ntentProvider、Socket、AIDL、Messager

  • Between the four components , Encapsulate data into Bundle. Starting another process in one process Activity perhaps Service, You can go through Intent hold Bundle Pass on the past . among , Packaged in Bundle The data in the needs to be able to be serialized

  • Use file sharing , Multiple processes read and write the same file , Get file content for interaction .

  • Use ContentProvider, Commonly used for multi process data sharing , For example, the album of the system , Music, etc , We can also pass ContentProvider Access to the

  • Use Socket To transmit data . Server side ( For example, a process runs Service) Create a ServerSocket object , Listen to the local port ; client ( For example, running in another process Activity) adopt Socket Connect to the local interface . after TCP After three handshakes , Establishing a connection . Then you can send data . Use socket It can not only realize inter process communication , Communication between devices can also be realized .

Binder

  • The basic principle :
    Android Peculiar IPC、 client - The server C/S The pattern of 、

Four characters :Client、Server、ServiceManager、BinderDriver

Call the process :
1. Server towards ServiceManager register
2. Client adopt ServiceManager obtain Server Proxy object of
3. Client Make a request to the proxy object , The request passed BinderDriver Send to Server Handle
4. Server adopt BinderDriver Return processing results

  • Be careful : The client calls the method of the server , Called method It runs on the server side Binder Thread pool in , here The client is suspended . Therefore, it is necessary to avoid ANR.(AIDL and Messager Empathy )

  • Binder Connection pool

There are multiple uses in one application AIDL Scene , There is no need for every AIDL Create your own Service. Instead, use a Service, Create and return one Binder The connection pool Binder object .Activity In the use of AIDL When , You can use this Binder Connect pool objects , Get different Binder object ( Similar to the factory model )

Android Analysis of electronic version of refined interview questions

AIDL

  • Usage flow : With Activity( process 1) and Service( process 2) For example, communication

  • establish AIDL Interface ,Build once , Generate relevant code

  • establish IBinder example , Instantiation xxx.Stub() Abstract inner classes ,override Abstract method

  • establish Service, stay onBind() in , Put the above IBinder The instance returned

  • stay Activity Call in bindService start-up Service, And then in ServiceConnection Medium onServiceConnected Method callback IBinder example .

  • Activity Call the method of the instance , Achieve communication

Messager

  • A lightweight cross process communication scheme , Bottom use AIDL Realization .

  • It's a kind of Serial communication , That is, the server needs to process messages one by one . therefore , In the case of a large number of concurrent requests , use Messager It's not suitable .

  • Usage flow : With Activity( process 1) and Service( process 2) For example, communication

  1. stay Service in new One Messenger( This Messenger You need to specify the Handler)
  2. And then in onBind Function , return messenger Of Binder object (messenger.getBinder())
  3. stay Activity in , adopt bindService start-up service, adopt ServiceConnection Get Binder object .
  4. Through this Binder Object instantiates a Messenger, then messenger.send(message) communicate

Start process

Android Startup process

init process -zygote process -SystemServer process - Various ManagerService(AMS,PMS,WMS)- launcher Program

App Start process

launcher-AMS-(pause)-zygote- New process ActivityThread-(main function )- towards AMS register - notice ActivityThread establish Activity And execute the lifecycle

App Inside Activity Start process

Activity1-AMS-(pause)- In the same ActivityThread- load Activity2 class , Execution lifecycle

ActivityManagerService and Instrument The difference between


Performance and optimization

apk Bag size

1、 Reduce unnecessary jar Packet dependency
2、 Use code first to set UI effect
3、 Remove unused resource files , Compress the size of other resource files , Don't fit all sizes of equipment
4、 Try to reuse code , Avoid code redundancy
5、 Limit app Supported by cpu Number of schemas : In the current Android In ecosystem , Let your app Support armabi and x86 Architecture is enough ;

The number of methods is out of bounds multiDex programme

  • what:dex yes Android On the platform (Dalvik virtual machine ) Of Executable file , amount to Windows Platform exe file , Every Apk There are... In the installation package dex file .

  • Single dex The file contains The maximum number of methods is 65536, contain Android Framwork、 Rely on the jar package , And all the methods of applying itself .

  • The number of solutions is out of bounds :

  1. Remove useless code and third-party libraries
  2. Adopt plug-in mechanism , Dynamic loading dex. This is a heavyweight scheme
  3. multiDex programme —— It can be downloaded from apk Load multiple dex file
  • Basic use :
  1. To configure Gradle, add to multiDexEnabled true
  2. add to multiDex rely on
  3. stay Application Add MultiDex.install(this) Code

other

The goal is :

  • fast : Fluent
  • steady : Stable
  • province : Save electricity 、 Flow saving
  • Small : The installation package is small

Optimization plan :

  • Layout optimization :

  • Reduce View The number of layers of the tree

  • Reasonable use gives priority to FrameLayout and LinerLayout, Reduce use RelativeLayout

  • Layout reuse , Use a label

  • OOM Optimize

  • ANR Optimize

  • ListView(GridView) Optimize

  • Use viewholder, Conduct view Reuse

  • Not in getview() Time consuming operation in

  • Bitmap Optimize

  • Picture compression

  • cache ( The core ): Memory cache and disk cache 、LRU Algorithm


framework : It is essentially a code architecture idea

MVC

among M Layers process data , Business logic, etc ;V Display results of layer processing interface ;C Layers act as bridges , To control V Layer and the M Layer of communication
View layer (View): It is generally used XML The file describes the interface , these XML It can be understood as AndroidApp Of View.
Control layer (Controller):Android Zhongyou Activit、Fragment To undertake , Responsible for logical processing
The model layer (Model): Provide data , From the database or network operations .

shortcoming : stay Android In development ,Activity It's not a standard MVC In the pattern Controller, Its primary responsibility is to load the layout of the application and initialize the user interface , Accept and process operation requests from users , And then respond , both view layer , again controller layer . With the increasing complexity of the interface and its logic ,Activity The responsibilities of class are increasing , So that it becomes huge and bloated .

MVP

  • MVP Frame by 3 Part of it is made up of :

  • Model: Provide data , From the database or network operations

  • View: Corresponding to Activity/Fragment etc. View, Mainly responsible for UI Show

  • Presenter: yes Model and View The bridge between , Do logical processing .View Not directly to Model To operate

  • advantage : Will be in Activty A large number of logical operations in Presenter In the control layer , avoid Activity The bloated .

  • shortcoming :MVP The pattern needs to write many new interfaces ; Too complex logic will make Presenter Overstaffed

  • Implementation method :

  • Definition IView Interface ,Activity Realization IView Interface , Then update... In the method UI;

  • stay Presenter Medium maintenance IView A reference to ;

  • stay Activity Instantiation in Presenter, And then IView Example ( namely this) Assign a value to Presenter.

  • stay Model Do specific operations in ,Presenter Get specific results , By calling the View Methods , to update UI.

MVVM

  • Model,View and ViewModel

  • Model: Provide data , From the database or network operations

  • View: Should be Activity/Fragment etc. View, Mainly responsible for UI Show ;

  • ViewModel Is responsible for logical processing ;Model Provide data .ViewModel and View Through binding , The coupling degree is further reduced

AAC(Android Architecture Components, Architecture components )

  • LiveData:

  • Using observer mode , Can be bound to a control , Monitor data changes and refresh UI.

  • Can sense the life cycle of the control , Automatically unregister when the control is destroyed , So there is no memory leak

  • ViewModel: Remove the data and logic of the view from entities with lifecycle characteristics ( Such as Activity and Fragment) Peel away . such as AndroidViewModel(ViewModle Subclasses of )

  • Room: Official database framework , For native SQLite API A layer of encapsulation .

  • And SQLite comparison : For complex database structures ,SQL Complex use , The code is long 、 Management is difficult ;Room, Easy to use 、 Easier to manage

MVVM and AAC

Personal understanding :MVVM It's an idea ,AAC Provides a variety of tools . utilize AAC Tool implementation in MVVM Thought

View:
Through binding , The coupling degree is further reduced

AAC(Android Architecture Components, Architecture components )

  • LiveData:

  • Using observer mode , Can be bound to a control , Monitor data changes and refresh UI.

  • Can sense the life cycle of the control , Automatically unregister when the control is destroyed , So there is no memory leak

  • ViewModel: Remove the data and logic of the view from entities with lifecycle characteristics ( Such as Activity and Fragment) Peel away . such as AndroidViewModel(ViewModle Subclasses of )

  • Room: Official database framework , For native SQLite API A layer of encapsulation .

  • And SQLite comparison : For complex database structures ,SQL Complex use , The code is long 、 Management is difficult ;Room, Easy to use 、 Easier to manage

MVVM and AAC

Personal understanding :MVVM It's an idea ,AAC Provides a variety of tools . utilize AAC Tool implementation in MVVM Thought

View:

copyright notice
author[m0_ sixty-four million three hundred and fourteen thousand four],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/02/202202041637547897.html

Random recommended