This is my recent collection of interview questions for students who plan to find jobs after the New Year. The knowledge involved in this article is relatively broad or may be relatively scattered, and I have omitted some basic knowledge (such as what are the four components of Android), some of which I have attached my own understanding, some of which have attached a detailed link to the relevant article. You can pick their own interest in the content to check, later I will continue to add.
Basic Components
How does the Activity lifecycle change when switching between vertical and horizontal screens?
1. If you do not configure Android :ConfigChanges, the system will take care of it by default, and the Activity will be rebuilt, and the Activity lifecycle will go through again.
With onRestoreIntanceState onSaveInstanceState () ()
2. If set android: configChanges = “orientation” | keyboardHidden | screenSize “>, the Activity of the life cycle will not retrace again, the Activity will not rebuild, Only the onConfigurationChanged method is called back.
The startActivity of an activity is different from the startActivity of a context
(1) When launching a new Activity from an Activity, you can simply launch McOntext.startactivity (Intent).
(2) If an Activity is launched from another Context, you must set a Flag for the intent:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ;
mContext.startActivity(intent);
Copy the code
This section describes how to start an Android application
The whole application startup process takes many steps, but overall, it falls into the following five phases:
The Binder communicates with the ActivityManagerService that it wants to start an Activity. ActivityManagerService notifies the Binder to enter the Paused state through the interprocess communication mechanism. 3. : The Binder communicates with ActivityManagerService that it is ready, Paused, and ActivityManagerService creates a new process. To start an ActivityThread instance, the Activity to be started will run in this ActivityThread instance. 4. : ActivityThread passes a Binder object of type ApplicationThread to ActivityManagerService through the Binder interprocess communication mechanism. So that ActivityManagerService can later communicate with this Binder object; ActivityManagerService notifies ActivityThread through Binder interprocess communication that it is now ready to actually start an Activity.Copy the code
Related article: Source code analysis of Android application startup process
How to ensure that the Service is not killed?
- Provide process priority to reduce the probability of process being killed. Method 1: Monitor the unlocking event of the mobile phone lock screen, start an Activity of 1 pixel when the screen is locked, and destroy the Activity when the user is unlocked. Method 2: Start the foreground service. Method 3: Upgrade the service priority: In the Androidmanifest.xml file, you can use the Android :priority = “1000” attribute to set the highest priority for an Intent-filter. 1000 is the highest value, and smaller numbers give lower priority.
- After the process is killed, pull method 1: register the high-frequency broadcast receiver and awaken the process. If the network changes, unlock the screen, boot, and other methods: two processes awaken each other. Method 3: Rely on systematic arousal. In onDestroy, restart the service: service +broadcast, which sends a custom broadcast when the service is in ondeStory. Restart the service when it receives a broadcast.
- Depending on the third party according to the different terminals, in the Mi phone (including MIUI) access to Mi push, Huawei phone access to Huawei push; Other mobile phones can consider to access Tencent carrier pigeon or Aurora push and Mi Push for A/B Test.
This section describes the Acitivty task stack and how to use it
The task stack is a last in, first out structure. The Activity at the top of the stack is in the focus state, and when the back button is pressed, the activities on the stack are removed one by one and their onDestory() method is called. 1, Standard: Default mode: Each startup creates a new Activity object and places it in the target task stack
2. SingleTop: Determine whether the same activity object exists at the top of the current task stack. If so, use it directly; if not, create a new activity object and put it on the stack
3, singleTask: the task stack will determine whether the same activity exists, if so, then will clear the activity on top of the other activity objects displayed, if not, will create a new activity on the top of the stack
4. SingleIntance: An activity is created in a new task stack, and only one activity instance is allowed in the task stack. Other components calling the activity use the activity object directly
Method one: use android: launchMode = “standard | singleInstance | single Task | singleTop” to control the Acivity Task stack. Intent Flags:
Intent intent=new Intent();
intent.setClass(MainActivity.this, MainActivity2.class);
intent.addFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Copy the code
FLAG_ACTIVITY_NEW_TASK is equivalent to singleTask Intent. FLAG_ACTIVITY_CLEAR_TOP is equivalent to singleTop
Activity Intent Flags and task-related properties
Context Related Issues
The Context of the Activity is different from that of the Service and Application. The Activity inherits from ContextThemeWraper. Each Activity, Service, and Application Context inherited from contextwrapp. is a new ContextImpl object getApplication() to retrieve the Application instance. But this method can only be called from activities and services. In most cases, we might want to use an Application in an Activity or Service, but in some other scenario, such as a BroadcastReceiver, we want to get an instance of the Application. You can use the getApplicationContext() method. GetApplicationContext () has a wider scope than getApplication(). Just call the getApplicationContext() method to get our Application object.
The number of contexts is equal to the number of activities + the number of services + 1, where 1 is Application. What about Broadcast Receiver, Content Provider? Broadcast Receiver and Content Provider are not subclasses of Context. The Context they hold is passed from other places, so they are not counted in the total number of Context.
How to create a Dialog in a Service
1. After we get the Dialog object, it is necessary to give it a set type, namely: the Dialog. The getWindow () setType (WindowManager. LayoutParams. TYPE_SYSTEM_ALERT)
2. Adding permission in the Manifest: < USES – permission android: name = “android. Permission. SYSTEM_ALERT_WINDOW” / >
The View article
Can non-UI threads update the UI?
So when you’re accessing the UI, ViewRootImpl will call the checkThread method to check which thread is currently accessing the UI, and if it’s not the UI thread then it will throw an exception and when you execute the onCreate method, the ViewRootImpl hasn’t been created yet, so you can’t check the current thread. The ViewRootImpl is created after the onResume method callback.
void checkThread() {
if(mThread ! = Thread.currentThread()) { throw new CalledFromWrongThreadException("Only the original thread that created a view hierarchy can touch its views."); }}Copy the code
A non-UI thread can refresh the UI if it has its own ViewRoot, that is, the same thread that updates the UI that created the ViewRoot, or if it updates the UI before executing checkThread().
Related article: Is it true that Android subthreads can’t update UI
Method to resolve ScrollView nested ListView and GridView conflicts
Override the ListView onMeasure method from the definition height:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
Copy the code
Examine the understanding of MeasureSpec’s three modes, related articles.
Customize View optimization policies
To speed up your view, minimize unnecessary code for frequently called methods. Start with onDraw, and be careful not to do memory allocation here because it will cause GC, which will cause a lag. Allocates memory during initialization or animation intervals. Do not do memory allocation while the animation is executing.
You also need to minimize the number of times onDraw is called, most of the time onDraw is caused by invalidate() calls. So try to minimize the number of invailDate () calls. If possible, call invalidate() with four arguments instead of invalidate() with no arguments. Invalidate without arguments forces the entire view to be redrawn.
Another time-consuming operation is to request a layout. Any time requestLayout() is executed, it causes the Android UI system to traverse the entire hierarchy of views to calculate the size of each View. If conflicting values are found, it will need to be recalculated several times. In addition, you need to keep the View hierarchy as flat as possible, which is very helpful for efficiency.
If you have a complex UI, you should consider writing a custom ViewGroup to perform its layout operations. Unlike built-in views, custom views allow the program to measure only that part of the view, which avoids traversing the entire view hierarchy to calculate the size. The PieChart example shows how to inherit a ViewGroup as part of a custom View. PieChart has sub-views, but it never measures them. Instead, he sets their size directly according to his own layout rules.
Thread article
Handler, Message, Looper and MessageQueue
Main Thread (UI Thread) Definition: When the application is first started, Android will start a Main Thread (Main Thread) function: the Main Thread is responsible for handling UI related events
Definition: Handler receives and processes the Message object (Bean object) function: communication related information storage and transfer
ThreadLocal definition: A ThreadLocal is an internal storage class that allows each thread to store its own private data. That is, after the data store, only in the specified thread to obtain the stored object, and other threads can not get the current thread stored the object. Function: Responsible for storing and obtaining Looper of this thread
MessageQueue (Message queue) definition: use a single linked list of data structure to store the Message list function: used to store the Message sent by the Handler, in the first in first out execution
Definition: The main role of Message Handler: responsible for sending messages to the Message queue & processing the messages dispatched by Looper
Looper (Looper) definition: acts as a bridge between Message Queue and Handler: Message loop: loops to fetch messages from the Message Queue. Message dispatch: delivers messages to the corresponding Handler
2. Draw your own diagram
3. How many ways can Handler send messages?
1, sendMessage(Message MSG) 2, Post (Ruunable r)
4. How many ways can Handler handle messages?
This is the source code for dispatchMessage() :
public void dispatchMessage(Message msg) {
if(msg.callback ! =null) {
//1. How to handle post() method
handleCallback(msg);
} else {
if(mCallback ! =null) {
if (mCallback.handleMessage(msg)) {
return; }}//2. The sendMessage() methodhandleMessage(msg); }}//1. The final processing method of the post() method
private static void handleCallback(Message message) {
message.callback.run();
}
//2. The final processing of the sendMessage() method
public void handleMessage(Message msg) {}Copy the code
Message, Handler, MessageQueue, Looper?
MessageQueue is a MessageQueue, which can store the messages sent by the Handler. It provides the methods of in-queue and out-queue to manage the MessageQueue. The principle of out-queue and in-queue is to use the data structure of single linked list to insert and delete. These are the enqueueMessage() and next() methods. Message is a Bean object with properties that record messages.
Looper is a loop that loops out messages from MessageQueue. It provides Looper initializes and loops out messages, namely prepare() and loop(). In the prepare() method, Looper is associated with a MessageQueue, and Looper is stored in a ThreadLocal. In the loop() method, Looper is retrieved through ThreadLocal. The next() method of MessageQueue is used to fetch the Message and determine whether the Message is empty. If yes, Looper blocks. If not, the Message is distributed to Handler through dispatchMessage() method. The Handler executes the handlerMessage() method, and since the handlerMessage() method is an empty method, that’s why you need to override the handlerMessage() method in the Handler. It is important to note that only one Looper can exist in a thread. In this case, a ThreadLocal is an object that holds a Looper for a different thread.
Finally, there is this Handler, which is the bridge between Looper and MessageQueue. The Handler internally provides a set of methods for sending messages. The Message is eventually stored in the MessageQueue via the enqueueMessage() method of the MessageQueue. We can use this Handler directly in the main thread because a Looper is created by default in the main method of the entry when the application starts.
Related articles: blog.csdn.net/qq_30379689…
6. Why does creating a Handler in a child thread throw an exception?
The Handler’s work is dependent on loopers. loopers (and message queues) belong to a thread (ThreadLocal is a data store class within a thread that stores data in a given thread but not in other threads) and are not accessible to other threads. So the Handler is indirectly bound to the thread. Therefore, to use Handler, you must ensure that the thread created by the Handler has Looper objects and starts the loop. Because there is no Looper in the child thread by default, an error will be reported. The correct way to use it is:
private final class WorkThread extends Thread {
private Handler mHandler;
public Handler getHandler(a) {
return mHandler;
}
public void quit(a) {
mHandler.getLooper().quit();
}
@Override
public void run(a) {
super.run();
// Create a Looper for this thread,
// Internal implementation
/ / 1. New stars ()
/ / 2. The lopper in step 1 is placed in a ThreadLocal. ThreadLocal is used to save data. The main application scenario is that the data between threads does not affect each other
/ / 3. New MessageQueue() in the constructor of Looper in step 1;
// A Looper is created for the thread pair. A Looper is created for the thread pair
// Students who do not know the mechanism of the message can look up the information, there are many online also very good.
Looper.prepare();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("WorkThread", (Looper.getMainLooper() == Looper.myLooper()) + ","+ msg.what); }};// Enable infinite loop processing of messages: dispatchMessage
Looper.loop();
// Note that the order of the three cannot be reversed
Log.d("WorkThread"."end"); }}Copy the code
HandlerThread
1. HandlerThread function
When multiple time-consuming tasks need to be executed in the system, each task will start a new thread to execute the time-consuming tasks. As a result, the system will create and destroy threads several times, which affects performance. To solve this problem, Google provides HandlerThread. HandlerThread is to create a Looper loop in the thread, and let Looper poll the message queue. When a time-consuming task enters the queue, it does not need to start a new thread, but just execute the time-consuming task in the original thread. Otherwise the thread blocks.
2. Advantages and disadvantages of HanlderThread
- HandlerThread is essentially a Thread class that inherits Thread;
- HandlerThread has its own internal Looper object, which can Looper loops;
- The looper object of the HandlerThread is passed to the Handler object
handleMessage()
Method to perform asynchronous tasks. - When HandlerThread is created, it must be called first
HandlerThread.start()
Method, Thread will first call the run method to create a Looper object. - The advantage of handlerThreads is that they are asynchronous and do not clog, reducing performance costs
- The disadvantage of handlerThreads is that they cannot continue to multitask at the same time and need to wait for processing, which is inefficient
- Unlike a thread pool, a HandlerThread is a serial queue with only one thread behind it.
IntentService IntentService IntentService IntentService IntentService
IntentService
-
It is essentially a special Service that inherits from a Service and is itself an abstract class
-
It can be used to execute time-consuming asynchronous tasks in the background and automatically stop when the task is complete
-
It has a higher priority and is less likely to be killed by the system (due to inheritance from services), so it is better suited for high-priority asynchronous tasks. It implements asynchronous operations internally through handlerThreads and handlers
-
When you create an IntentService, you simply implement the onHandleIntent and constructor. OnHandleIntent is asynchronous and can perform time-consuming operations
-
Even if we start the IntentService multiple times, there is only one instance of the IntentService, just like a traditional Service. Eventually the IntentService will call onHandleIntent to execute the asynchronous task.
-
When the task is complete, IntentService will stop automatically, instead of calling stopSelf() manually. In addition, IntentService can be started multiple times, and each time-consuming operation will be executed as a work queue in the IntentService’s onHandlerIntent() callback method, and only one worker will be executed at a time.
IntentService IntentService IntentService IntentService IntentService
AsyncTask
1. What is AsyncTask
AsyncTask is a lightweight asynchronous task class that executes background tasks in a thread pool and then passes the progress and final results to the main thread to update the UI in the main thread. AsyncTask makes it easier to execute background tasks and access the UI in the main thread. However, AsyncTask is not suitable for time-consuming background tasks, for which a thread pool is recommended.
2. How to use AsyncTask
Three parameters Params: indicates the type of parameters that will be passed to the doInBackground() method of AysncTask Progress: Result: Indicates the parameter type of the Result returned by the background task. This parameter is used as a parameter to the onProgressUpdate() method. DoInBackground () : Execute the asynchronous task, onProgressUpdate() in the thread pool: Callback when publishProgress is called in doInBackground, onPostExecute() in the main thread: after the asynchronous task has been executed, and onCancelled() in the main thread: when the asynchronous task has been cancelled
3, AsyncTask memory leak cause: non-static inner class holds an anonymous reference to the external class, causing the Activity to be unable to release. AsyncTask internally holds a weak reference to the external Activity. AsyncTask is changed to a static inner class called asyncTask.cancel () in the Activity’s onDestory().
4. The resulting loss of screen rotation or the Activity being killed in the background will cause the Activity to be recreated. The previously running AsyncTask will hold a reference to the previous Activity that is no longer valid. Calling onPostExecute() to update the interface will no longer take effect.
Before Android 2.3, AsyncTask uses parallel execution by default. After Android 2.3, AsyncTask uses serial execution by default. If you need to use parallel execution after Android 2.3, You can call AsyncTask’s executeOnExecutor();
6. Internal thread pool of AsyncTask
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
SDefaultExecutor is an instance of SerialExecutor, and it is a static variable. That is, all AsyncTask objects in a process share the same SerialExecutor object.
Related article: Android multithreaded -AsyncTask in-depth analysis of the working principle
Some interview tips
In general, the first round is a basic interview, which requires a solid foundation, the most commonly used Android basic knowledge, Java basic knowledge and understanding of the principles of some common things, such as handler, Thread and other technical points in the project
In the second round, you need to learn more about Android event distribution mechanism, Android drawing mechanism, Windows Manager related knowledge, inter-process transfer, Java memory management mechanism, some common list,map principles, and the differences between subclasses
Can enter the third round of the basic problem, but should pay attention to the following questions The wheel is the boss or head, ask questions generally see the depth and breadth When asked about salary, to say a proper, random small companies, big companies must be careful, when uncertainty, can tell each other, let the other side to give a reasonable salary. Are generally in the original salary base on the growth, listen to the headhunter said that the general increase in 15%-30%, super NB can be 30% and above, if you feel good, very powerful, the highest recommendation 20%, the average person is set in 15% or so the most reliable. There is usually a set of mechanisms within the company, depending on the company. This is a difficult question to answer. If it’s not in line with the direction of the company, it’s probably not going to work for the company. It is recommended to be tentative and ask what the company is missing and what you can offer. Of course, for those who pursue their own, it can be assured of bold mention. My direction is the architect, ha ha ha, quite extreme, don’t learn me oh. I feel like choices go both ways, so I know what I need. What UI are you best at or what else? This question is even harder to answer. If you say you’re good at UI, does that mean you’re not good at anything else? Although I do not know the intention of the interviewer, but I can feel that this question is not so easy to answer, I will answer that I can do whatever business to meet whatever needs. Maybe the answer is not very good, in short and the company’s position match on the line, so that it is not wrong. Excerpt from the article: a five-year Android developer Baidu, Ali, Jumei, Inke interview heart
Resume template recommendation:
Github.com/Trinea/trin…
Github.com/geekcompany…
More interview questions:
www.jackywang.tech/AndroidInte… Github.com/AweiLoveAnd… Github.com/hadyang/int… Jingbin. Me / 2017/02/20 /… Github.com/Freelander/… www.jianshu.com/p/1d3a2227f… Github.com/stormzhang/… www.zhihu.com/question/37… (3-5 years of experience)
Web site
Lintcode: Answer link
Cattle guest