The most complete collection of the latest Android interview questions in 2022 in history (including answers + source code)

insert image description here
Gold three silver four, it is the annual golden job-hopping season again, presumably there may be many Android programmers starting to gear up, just around the corner. However, most of the interview questions on the Internet are outdated or even full of mistakes, full of loopholes. Today, I combined my interview experience during this period of time and the exchanges between major manufacturers and experts in several Android technology groups to summarize the latest 2022 interview questions. A collection of Android interview questions. So, without further ado, let's get right to the point.

foreword

The first thing to declare is: the purpose of the interview questions is not to let everyone recite the questions, but to help everyone review from different dimensions and learn from each other. Let's get down to business:

Summary of interview questions

1. Four major components of Android: Activity, Service, BroadcastReceiver, ContentProvider. Their functions are respectively:

Activity—>Cooperate with View to display interface
Service—>Run in the background for a long time without directly interacting with users
BroadcastReceiver—>Receive broadcast
ContentProvider—>Provide data for other modules to use

2. How many launch modes does Activity have? What are the characteristics of each?

1. Standard (the default startup mode)
When we send an intent to start the Activity, the Activity is always created a new instance.
2. singleTop (stack top multiplexing)
If you want to start an Activity that exists in the task stack and is at the top of the task stack, a new Activity instance will not be created, but the onNewIntent() method of the Activity will be called to avoid the top of the stack The Activity is created repeatedly. If an instance of the called Activity already exists but is not at the top of the stack, the called Activity will still be created.
3. singleTask (in-stack multiplexing)
Activity will only have one instance in the task stack. If the Activity to be started already exists in the task stack Task, a new Activity instance will not be created, but the existing Activity will be reused, the onNewIntent() method will be called, and all other activities above the Activity task stack will be cleared
4.singleInstance (single instance mode)
The Activity with this mode can only be located in a single task stack, and cannot have other Activities. Any other activities started from this Activity will be placed in other task stacks.

3. How many types of Service are there? What are the application scenarios for each?

method start method way to stop Methods for communicating with started components life cycle
startService After calling the startService() method in other components, the service is in the started state After the stopSelf() method is called in the service, or the stopService() method is called by other components, the service will stop running No default communication method is provided, and the service is running independently after starting the service Once started, the service can run indefinitely in the background, even if the component that started the service has been destroyed, it will not be affected until it is stopped
bindService After calling the bindService() method in other components, the service is in the started state After all components bound to the service are destroyed, or they all call the unbindService() method, the service will stop running Can communicate through ServiceConnection, components can interact with service, send requests, get results, and even use IPC to perform these operations across processes When all components bound to it are unbound (maybe the component is destroyed or it may call the unbindService() method), the service will stop

4. What is the application scenario of LaunchMode?

There are four types of LaunchMode, namely Standard, SingleTop, SingleTask and SingleInstance. The implementation principle of each mode is described in detail on the first floor. The specific usage scenarios are described below:

  • Standard:
    Standard mode is the default startup mode of the system. Generally, most of the pages in our app are composed of pages of this mode. The more common scenario is: in social applications, click to view user A information->view user A fans- >Select and view user B information from fans -> view user A fans... In this case, we generally need to keep all the execution sequences of the pages of the user's operation activity stack.
  • SingleTop:
    The SingleTop mode is commonly used in notification bar behaviors in social applications. For example, when an App user receives several push messages requested by friends, the user needs to click on the push notification to enter the personal information page of the requester, and set the information page to SingleTop mode. Reusability can be enhanced.
  • SingleTask:
    The SingleTask mode is generally used as the homepage of the application, such as the homepage of the browser. The user may start the browser from multiple applications, but the main interface is only started once. In other cases, onNewIntent will be used, and other pages on the main interface will be cleared.
  • SingleInstance:
    The SingleInstance mode is often used in applications with independent stack operations, such as the reminder page of the alarm clock. When you watch a video in application A, the alarm clock rings. You click the alarm notification and enter the reminder details page, and then click Back to return to the page again. Go to A's video page, so that it will not interfere too much with the user's previous operations.

5. Background and foreground Service

This involves the classification of Service.
If it is classified by whether it is insensitive or not, Service can be divided into foreground and background. The foreground Service will let the user perceive that there is such a thing running in the background through notification.
For example, music apps, while playing music in the background, can find that there is always a notification displayed in the foreground, letting users know that there is such a music-related service in the background.
In Android 8.0, Google requires that if the program is in the background, then the background service cannot be created, and the background service that has been started will be stopped after a certain period of time.
Therefore, it is recommended to use the foreground Service, which has a higher priority and is not easy to be destroyed. The method of use is as follows:

startForegroundService(intent);
    public void onCreate() {
        super.onCreate();
        Notification notification = new Notification.Builder(this)
                .setChannelId(CHANNEL_ID)
                .setContentTitle("主服务")//标题
                .setContentText("运行中...")//内容
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
        startForeground(1,notification);
    }  

    <!--android 9.0上使用前台服务,需要添加权限-->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

What about background tasks? The official recommendation is to use JobScheduler.
6. Talk about JobScheduler
task scheduling JobScheduler, Android5.0 was launched. (Some friends may feel unfamiliar, in fact, it is also implemented through Service, which will be discussed later) What
it can do is to perform automatic task execution under your specified requirements. For example, it will automatically run in the background under various circumstances such as the specified time, when the network is WIFI, when the device is idle, and when it is charging.
So Google let it replace some of the functions of the background Service, use cases:

  • First, create a JobService:
public class MyJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters params) {
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }
}
  • Then, register this service (because JobService is also a Service)
<service android:name=".MyJobService"
    android:permission="android.permission.BIND_JOB_SERVICE" />
  • Finally, create a JobInfo and execute
JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);  
 ComponentName jobService = new ComponentName(this, MyJobService.class);

 JobInfo jobInfo = new JobInfo.Builder(ID, jobService) 
         .setMinimumLatency(5000)// 任务最少延迟时间 
         .setOverrideDeadline(60000)// 任务deadline,当到期没达到指定条件也会开始执行 
         .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)// 网络条件,默认值NETWORK_TYPE_NONE
         .setRequiresCharging(true)// 是否充电 
         .setRequiresDeviceIdle(false)// 设备是否空闲
         .setPersisted(true) //设备重启后是否继续执行
         .setBackoffCriteria(3000,JobInfo.BACKOFF_POLICY_LINEAR) //设置退避/重试策略
         .build();  
 scheduler.schedule(jobInfo);

Simply put the principle:

JobSchedulerService is a service started in SystemServer, and then traverses unfinished tasks, finds the corresponding JobService through Binder, executes the onStartJob method, and completes the task. For details, see the analysis of the reference link.
So I know that after 5.0, if you need to execute background tasks, especially tasks that need to meet certain conditions, such as network power, etc., you can use JobScheduler.
Some people may ask, what should I do before 5.0?
You can use GcmNetworkManager or BroadcastReceiver to handle task requirements in some cases.
Google also took this into consideration, so it combined JobScheduler after 5.0 with GcmNetworkManager, GcmNetworkManager, AlarmManager before 5.0 and task-related APIs to design WorkManager.
7. Talk about WorkManager

WorkManager is an API that allows you to easily schedule deferrable asynchronous tasks that should run even after quitting the app or rebooting the device.

As a member of Jetpack, it is not very new. Its essence is to combine the existing APIs related to task scheduling, and then execute these tasks according to the version requirements. There is a picture on the official website: So what can WorkManager do

? ?

1. It can perform well for some task constraints, such as tasks that need to be performed under conditions such as network, device idle state, and sufficient storage space.
2. It can perform tasks repeatedly, one-time and stably. Including the ability to continue the task after the device is restarted.
3. You can define the cohesive relationship of different work tasks. For example, set one task after another.
In short, it is a great tool for performing tasks in the background.

8. Talk about the difference between startService and bindService, life cycle and usage scenarios?

  1. difference in life cycle

When executing startService, Service will experience onCreate->onStartCommand. When executing stopService, call the onDestroy method directly. If the caller does not stopService, the Service will always run in the background, and the next time the caller wakes up, he can still stopService.

When executing bindService, Service will experience onCreate->onBind. At this time, the caller is bound to the Service. When the caller calls the unbindService method or the caller Context does not exist (such as the Activity is finished), the Service will call onUnbind->onDestroy. The so-called binding together here means that the two coexist and die.

If startService is called multiple times, the Service can only be created once, that is, the onCreate method of the Service will only be called once. But every time startService is called, onStartCommand method will be called. The onStart method of Service was deprecated in API 5, and it was replaced by the onStartCommand method.

When the bindService is executed for the first time, the onCreate and onBind methods will be called, but when the bindService is executed multiple times, the onCreate and onBind methods will not be called multiple times, that is, the service will not be created and bound multiple times.

  1. How does the caller obtain the method of the bound Service

The onBind callback method will return an instance of the IBinder interface to the client. IBinder allows the client to call back the method of the service, such as getting the running status of the Service or other operations. We need the IBinder object to return a specific Service object to operate, so the specific Service object must first implement the Binder object.

  1. What about using both startService and bindService?
    If a Service is started and bound again, the Service will always run in the background. First of all, no matter how it is called, onCreate will always be called only once. Corresponding to how many times startService is called, how many times the Service's onStart method will be called. The termination of Service needs to call unbindService and stopService at the same time. Regardless of the calling order of startService and bindService, if you call unbindService first, the service will not terminate automatically at this time, and then stopService will be called before the service will terminate; if stopService is called first, the service will not be terminated at this time, and call unbindService or before The service will stop automatically after the Context that calls bindService no longer exists (such as when the Activity is finished).

So, under what circumstances do you use both startService and bindService?

If you just want to start a background service for a long-term task, then use startService. If you still want to get in touch with the running Service, there are two ways: one is to use broadcast, and the other is to use bindService. The disadvantage of the former is that if the communication is more frequent, it is easy to cause performance problems, while the latter does not have these problems. Therefore, in this case, startService and bindService need to be used together.

In addition, if your service only exposes a remote interface for the connected client (Android Service is a C/S architecture) to remotely call the execution method, at this time you can not let the service run at the beginning, but just bindService, so that Only when you bindService for the first time will you create an instance of the service to run it, which will save a lot of system resources, especially if your service is a remote service, then the effect will be more obvious (of course, it will take a certain amount of time to create it in Servcie time, this needs attention).

  1. Local service and remote service

Local services are attached to the main process, which saves resources to a certain extent. Because the local service is in the same process, it does not need IPC or AIDL. Corresponding bindService will be much more convenient. The disadvantage is that after the main process is killed, the service will terminate.

The remote service is an independent process, and the format of the corresponding process name is the package name plus the android:process string you specified. Since it is an independent process, even if the process where the Activity is located is killed, the service is still running. The disadvantage is that the service is an independent process, which will occupy certain resources, and using AIDL to perform IPC is a little troublesome.

For startService, whether it is a local service or a remote service, the work we need to do is equally simple.

9. How does Service keep alive?

Use system broadcast to pull activity
Use system service to pull activity
Use Native process to pull activity <Android 5.0 and later fail> fork to monitor the main process, use native to use
JobScheduler mechanism to use JobScheduler mechanism to use <Android 5.0 and later>
use account synchronization mechanism to pull activity

10. What is the reason for the thread to update the UI and cause the crash?
In the trigger drawing method requestLayout, there is a checkThread method:

void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

Among them, mThread is compared with the current thread. And mThread is assigned when ViewRootImpl is instantiated.

So the reason for the crash is that the thread when the view is drawn to the interface (that is, the thread when ViewRootImpl is created) and the thread when the UI is updated are not the same thread.

11. The relationship between Activity, Dialog, PopupWindow, Toast and Window
This is an extended question, let me briefly talk about it from the perspective of creation method:

Activity. The PhoneWindow created during the Activity creation process is the smallest hierarchical Window, called the Application Window, with a hierarchical range of 1-99. (A Window with a large hierarchy can cover a Window with a small hierarchy)
Dialog. The display process of Dialog is basically the same as that of Activity. It also creates PhoneWindow, initializes DecorView, and adds the view of Dialog to DecorView, and finally displays it through addView.
But one difference is that the Window of Dialog is not an application window, but a sub-window, with a hierarchical range of 1000-1999. The display of the sub-window must be attached to the application window and also cover the application-level window. This is why the context passed in by the Dialog must be the Context of the Activity.

PopupWindow. The display of PopupWindow is different. Instead of creating PhoneWindow, it directly creates a View (PopupDecorView), and then displays it through the addView method of WindowManager.
If PhoneWindow is not created, does it have nothing to do with Window?

No, in fact, as long as the addView method of WindowManager is called, a Window is created, regardless of whether you have created a PhoneWindow or not. View is the manifestation of Window, but the existence of PhoneWindow makes the image of Window more three-dimensional.

Therefore, PopupWindow is also displayed through Window, and its Window level belongs to sub-Window, which must be attached to the application window.

Toast. Toast is similar to PopupWindow, there is no new PhoneWindow, and the View can be displayed directly through the addView method. The difference is that it belongs to the system-level Window, and the level range is 2000-2999, so it does not need to be attached to the Activity.
Comparing the four, it can be found that as long as you want to display View, the addView method of WindowManager will be involved, and the concept of Window will be used, and then it will be displayed and overlaid on the interface according to different layers.

The difference is that Activity and Dialog involve more complex layouts and elements such as layout themes, so PhoneWindow is used for decoupling to help them manage View. The structure of PopupWindow and Toast is relatively simple, so directly create a View similar to DecorView, and display it on the interface through addView.

12. What are extension functions in Kotlin

The extension function in kotlin actually adds a static final method to its own class, and the class that needs to be extended is passed into the method as the first parameter when it is used, and then used:

fun String.hello(str: String): String{
    return "hello" + str + this.length
}
 
fun String.hello1(str: String): String{
    return "hello$str"
}

After decompilation, the generated bytecode is as follows:

public final class ExtensionTestKt {
   @NotNull
   public static final String hello(@NotNull String $receiver, @NotNull String str) {
      Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
      Intrinsics.checkParameterIsNotNull(str, "str");
      return "hello" + str + $receiver.length();
   }
 
   @NotNull
   public static final String hello1(@NotNull String $receiver, @NotNull String str) {
      Intrinsics.checkParameterIsNotNull($receiver, "$receiver");
      Intrinsics.checkParameterIsNotNull(str, "str");
      return "hello" + str;
   }
}

The extension function in kotlin is actually implemented by adding a public static final function to the class, which can reduce the use of utils classes.

Extension functions are statically resolved and are handled using the process of static dispatch. This means that the extension function called is determined by the type of the expression in which the function is called, not by the result of the expression's runtime evaluation. This means that when using this extension function, if the class itself and its subclasses both extend the same function, this function will not be rewritten. When using it, it will only be used as needed. The actual type of the object of the method is used to determine which one is called, which is equivalent to calling a static method. instead of dynamic dispatch.

Summarize

These daily questions organized this time are some programming questions, some of which are problems that we may encounter in our daily development. By doing these questions, you can also test your mastery of these practical programming skills. A question every day, a little bit of growth every day.

If you feel that your learning efficiency is low and you lack correct guidance, you can refer to the following learning routes that I have collected and organized over the years of work, as a reference for everyone:

  1. Determine the direction and sort out the growth roadmap

mind Mapping

After the knowledge is sorted out, it is necessary to check for gaps.

  1. Watch the video for systematic learning

Because I am in the mobile development industry, I studied blindly in the past few years. As a result, when the interviewer asked me during the interview, my mind went blank for a moment. Only then did I find that my technology was too fragmented, and I was not deep enough or systematic enough about Android. At that time, I made up my mind: to conduct a systematic study again. What I lacked was systematic knowledge, and what was lacking was structural framework and ideas, so I decided to follow a teacher's video to learn systematically, which was more effective and more comprehensive. Regarding video learning, I personally recommend that you go to station B to study. There are many learning videos on station B. The only disadvantage is that because it is free, some technologies are easily outdated, and some related to copyright will be removed from the shelves.

  1. Learn systematically through source code

As long as you are a programmer, whether it is Java or Android, if you don’t read the source code and only look at the API documentation, you will just stay on the surface, which is not good for the establishment and completion of our knowledge system and the improvement of actual combat technology.

"The programming language is the way programmers express, and the architecture is the programmer's perception of the world." Therefore, if programmers want to quickly recognize and learn the architecture, it is essential to read the source code. Reading source code is to solve problems + understand things, and more importantly: to see the idea behind the source code; programmers say: read thousands of lines of source code, practice thousands of practices.

The real thing that can exercise your ability the most is to read the source code directly, not limited to reading the source code of major systems, but also including various excellent open source libraries. Of course, it is essential to knock it out with your own hands, and you will eventually feel shallow when you get it on paper, and you will never know that you have to do it yourself.

  1. Resume is well prepared

You can go to Zhihu to search for posts about resumes written by others, how to prepare, attract HR, highlight your own strengths and abilities, or ask a friend to help you see if there are any problems with your resume, such as being too simple or exaggerated, without focus, etc.

Try to summarize your highlights in one concise sentence, with numbers to illustrate its impact and significance.

Secondly, add interactive and displayable content to your resume, which can show your unique abilities.

  1. Brush questions to prepare for the battle, directly to the big factory

Within a week before the interview, you can start to sprint for the questions. Please keep in mind that when writing questions, technology is given priority and algorithms are basic, such as sorting. Intellectual questions, unless they are recruited by the school, are generally not asked much.

Finally, friends who need it can add the QR code below to reply to JJ to receive it for free, we promise 100%免费
]

Guess you like

Origin blog.csdn.net/B1ueSocks/article/details/123556452