---
# System prepended metadata

title: Android interview questions with answers

---

# Android interview questions with answers 
### What are Android Core Building Blocks
**Activity** - the building block of an interface. A window. 
**Services** - designed to keep running in the background. But android can kill them anytime, so they are usually bounded with notification widget. (?)
**Content Providers** - provide a level of abstraction for any data stored on the device that is accessible by multiple applications.
**Broadcast Receivers** - the system will send broadcasts from time to time for some systems signals, like battery getting low. 

### What is Intent?
An intent encapsulates a request, made to an Android, for some activity or other receiver to do something. Action + context. There are two types of intents:
* Explicit - invoke the activity class 
* Implicit - invoke the system components 

### Can the bytecode that is written in java be run on android?
No

### What is ART?
Android Runtime
Managed Runtime used by apps instead of Dalvik runtime. Performs the translation of the app's bytecode into native instructions that are later executed by the devices runtime environment. Used from Android 5.0

### JIT vs AOT
JIT - Just-In-Time compilation compiles each instruction at the time it is being executed. Dynamically at runtime.

AOT - Ahead-Of-Time from android 4.4 statically compiles all instruction at install time using dex2aot tool. Stores the result data on device to improve run-time performance.

![](https://i.imgur.com/AnPmcnl.png)

### What must contain intent-filter?
Must contain `action`
May contain `type` and `category`

### If android wants to kill the process, how it decides what to kill? 
Based on order of importance: 
1. Foreground process. User currently working with. Any of those conditions: 
    - Running ```Activity``` on top of the sscreen. (called ```onResume()``` method - RESUMED state)
    - Has a BroadcastReceiver that is currently running. (```BroadcastReceiver.onReceive() is execuring```)
    - Service that is executing one of its callbacks (```Service.onCreate()```, ```Service.onStart()```, ```Service.onDestroy()```)
2. Visible process, that the user is currently aware of
    - Running ```Activity``` that is visible but not in foreground (called ```onPause()``` - PAUSED state)
    - Foreground service, through ```Service.startForeground()``` 
    - Service that the system is using for a particuar feature that the user is aware, such as a live wallpaper, input method seervice

### If a parent activity has different permissions in their manifest can it launch activity? 
No
A parent activity cannot launch a child activity unless both activities have the same permissions in their manifest

### ART vs Dalvik
![](https://i.imgur.com/BmNK4qG.png)

- One GC Pause instead of two
- Loop optimization: bounds check, induction variables eliminated
- Faster native calls with special annotations
- Improve battery life 
- Improved startup time since the code is directly executed
- Faster runtime because of AOT 
- Futher optimization of dex files in Android 9+
- Better debuging support 

![](https://i.imgur.com/noMzbsR.png)

### What is GC optimization in ART 
- One pause instead of two 
    - Dalvik first pause - which mostly root marking - is done concurrently in ART by getting the threads to mark there own root 
- Parallelized processing in the second pause (before Sweeping phase)
- Increased GC throughput enabled by the sticky CMS collector 
- Reduce total time when clean up recently-allocated short-lived objects 
- Performs heap compaction - when app changes process state to background or cached - to reduce background memory usage 

### Describe the life of APK
![](https://i.imgur.com/OgqilbS.png)

### What is least privilage principle
By default the app get only access to the resources that are needed by the app to do the work and no more 

### How an application can share data with other apps 
Different apps might have the same linux user id. Such apps will also run in the same linux process and in the same VM. They have to be signed with the same certificate. 
Also the app can request the access the devices data and the user might explicitly give a permission for that.

### What is AAPT? 
AAPT is an acronym for Android Assets Packaging Tool. It handles the packaging process. 

### What is Fragment? 
The fragment is a part of Activity by which we can display multiple screens on one activity.

### What is ViewGroup?
View Group is a collection of views and other child views. It is an invisible part and the base class for layouts. 

## How to keep screen unblocked? 
- Set ```window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)``` or  android:keepScreenOn="true"> in xml. Unlike wake locks you don't have to worry about resources 
- Use Wake Locks
    - Declare a permission in manifest 
    - Require it with Broadcast Receiver or 
    - ```val wakeLock: PowerManager.WakeLock =
        (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
            newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag").apply {
                acquire()
            }
        }
        ```
    - wakeLock.release()
## Where to use Wake Locks? 
Never use wake lock in activity. Good case is with service that have to keep CPU busy even while the screen is turned of
### What is Context? 
Context is how we can get the information regarding activity and application. Also `Context` is like a handle to the system, it provides access to the resources, databases, preferences, etc.

### Fragment lifecycle 
![](https://i.imgur.com/QpHiQFE.png)

### Про фрагменты и конструктор, почему нельзя передавать через конструктор
[2] Если андроид решит переделать фрагмент, то он вызовет контруктор стандартный без аргументов и возникнет ошибка

### Под каким тэгом пишутся uses-permission в манифесте?
Под корнем, тэгом manifest

### Как хендлить разворот экрана 
[3] `android:configChanges` - will not recreate activities and fragments, but just use the same layout and call `onConfigurationChange` in the fragmens. 
Drawbacks: If you want to change something on screen rotation, like recreating layout, you will have to do that manually which is a lot of work. 
`Fragment.setRetainInstance(true)` - similar to `android:configChanges`. It signals to Android that you want ot continue using the same instance of the current Fragment. Parent Activity will be destroyed. Bad idea for the same reason 
`android:screenOrientation` - just forbid to change orientation
**Saving State** - just place all the data into bundles in `onSaveInstanceState` To restore the data, check savedInstanceState argument in onCreate method or you can override `onRestoreInstanceState`. It calls after `onStart` and before `onResume`. In Fragment you can check `savedInstanceState` in onCreate, onCreateView, onActivityCreated, or onViewStateRestored. Or you can override 'onViewStateRestored'
To store a lot of data use `Fragment` [4] The fragment can contain references to objects that you want to keep stateful. When Android shuts down your Activity due to configuration changes, the identified fragments in your Activity will not be destroyed. 
:::spoiler Example code
``` Java
public class retainFragment extends Fragment {
    //Instance references to be saved
    private Bitmap  btmap;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Disable fragment recreation
        setRetainInstance(true);
    }
    
    public Bitmap getBtmap() {
        return btmap;
    }

    public void setBtmap(Bitmap btmap) {
        this.btmap = btmap;
    }
}
```
:::

### Чем плох AsyncTask 
Создает memoryLeak потому что не привязан к activity lifecycle 

### The last callback in the lifecycle of an activity is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory. Usually, the system will call onPause() and onStop() before calling onDestroy(). Describe a scenario, though, where onPause() and onStop() would not be invoked.

### What is difference between Serializable and Parcelable ? Which is best approach in Android?

Parcelable stays to be faster. But I saw test and it seems like there is no big difference. Parcelable requires more things to override by hands, but with @Parcelize android annotation Kotlin generates everything automatically. 

Serializable uses reflection, that is why it is believed to be much slower process. Also it creates a lot of temporary objects. GC has more work to do. 
### Про Retrofit enqueue и execute 


## Activity
### Activity lifecycle
![](https://i.imgur.com/jFJdUN4.png)

### Can you change the name of the Activity?
Better not to. It might break app shortcuts


## Services 
### What is services?
It is an application component that can perform long-running operations in the background. It doesn't have UI. It is semi-independent from activity, i.e. it can run for some time even when a user switched to another app. Additionaly it can be used for IPC (interprocess communication). 

### Does Service create its own process?
No. It uses the same process as an app and it runs in the main thread by default. 

### What types of services exist? 
#### Foreground
This service is noticable by user. Audio app uses such services to play music. Such service has to display notification. Such service continues running even if the user doesn't interact with an app. The notification cannot be dismissed unless the service is either stopped or removed from the foreground. 

State-of-the art is to use WorkManager instead of Foreground service. 

Foreground service must show a status bar notification that has a priority of ```PRIORITY_LOW``` or higher. The notification cannot be dismissed unless the service is either stopped or removed from te foreground.
#### Background
It is not directly noticed by user

From API 26 the system imposes restricitons on running background services. Preferably use WorkManager. 
#### Bound 
Application calls ```bindService()```. Such service offers client-server interface so application can interact with such service. Can be used even accross processes with IPC. Such service runs as long as its bounded parent. Also killed when all parents unbind form it. 

### What will happen if the foreground service uses notification with lower priority then ```PRIORITY_LOW```?
Android adds a message to the notification drawer, alerting the user to the app's use of a foreground service. 

### What are started and bounded services? 
It is just a fact if the service implementation has its own ```onStartCommand()``` and ```onBind()``` methods. Those two methods can be implemented in the same service. Such service might work both: like the started service and like the bounded service.

The started service lifecycle is independent from the lifecycle of component that started it. Hence the service has to stop itself by calling stopSelf() or another component can call stopService().

The bound service generally doens't allow components to *start* it by calling ```startService()```. Use such service when you want to interact with the service from activities and other components in your application or to expose some of your application's funtionality to other applications through IPC.

### How to start Service? 
With ```Intent``` 
startService(Intent)
startForegroundService(Intent)

### How to decide do we need to use a service or a thread?
If some task has to be done in the background but only while application is running then use the thread in, for instance, Activity.

Still service is running in main thread, so if you what anything to run in the background start a new thread. 

### How to create a started service (maybe implement an example service on paper)
1. Create subclass of ```Service``` or its children 
2. Probably you will need a new thread in the service
3. Declare a service in the manifest
4. Call ```startService()``` with an intent. The service will receive an ```Intent``` in a ```onStartCommand()``` method
5. Override ```onStartService()``` method of the service lifecycle
6. Return one of the integer constants from the ```onStartService()``` method

### What are possible constants that are returned from ```onStartService()``` method?
#### ```START_NOT_STICKY```
After the service is killed do not recreate the service unless there are pending intents to deliver. The safest option to avoid running your service when not necessary
#### ```START_STICKY```
After the service is killed, the system will recreate the service but will not redeliver the last intent. The system calls ```onStartCommand()``` with a null intent unless there are pending intent to start service. 
#### ```START_REDELIVER_INTENT```
After the service is killed, the system will recreate the service and call ```onStartCommand()``` with the last intent that was delivered to the service. Any pending intent is delivered in turn. This is suitable for a services that are actively performing a job such as downloading a file. 
### Example of Service
:::spoiler Service code
``` Kotlin
class HelloService : Service() {

    private var serviceLooper: Looper? = null
    private var serviceHandler: ServiceHandler? = null

    // Handler that receives messages from the thread
    private inner class ServiceHandler(looper: Looper) : Handler(looper) {

        override fun handleMessage(msg: Message) {
            // Normally we would do some work here, like download a file.
            // For our sample, we just sleep for 5 seconds.
            try {
                Thread.sleep(5000)
            } catch (e: InterruptedException) {
                // Restore interrupt status.
                Thread.currentThread().interrupt()
            }

            // Stop the service using the startId, so that we don't stop
            // the service in the middle of handling another job
            stopSelf(msg.arg1)
        }
    }

    override fun onCreate() {
        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND).apply {
            start()

            // Get the HandlerThread's Looper and use it for our Handler
            serviceLooper = looper
            serviceHandler = ServiceHandler(looper)
        }
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show()

        // For each start request, send a message to start a job and deliver the
        // start ID so we know which request we're stopping when we finish the job
        serviceHandler?.obtainMessage()?.also { msg ->
            msg.arg1 = startId
            serviceHandler?.sendMessage(msg)
        }

        // If we get killed, after returning from here, restart
        return START_STICKY
    }

    override fun onBind(intent: Intent): IBinder? {
        // We don't provide binding, so return null
        return null
    }

    override fun onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show()
    }
}
```
:::

### What is ```IntentService```? 
It is a service that uses a worker thread to handle all of the start requests one at a time. It does job in another thread. But it is not recommended for use since it will not wok starting with Android 8 Oreo. Use ```JobIntentService``` instead

### What is ```JobIntentService```?

### How to choose between JobIntentService, IntentService, WorkManager and Service as a base class?
Don't use IntentService never ever. It doesn't work from Android 8 Oreo, due to the inroduction of Background execution limits.

### What is background execution limits?


### How to create a IBinder interface? 
1. Extend the Binder class 
    - The easiest way. Use it in case the service is private to an application and is in the same process as an application. Extend Binder class. 
2. Using a Messenger
    - If you need to communicate with other processes, create with a Messenger. The service defines a ```Handler``` that responds tp different types of ```Message``` objects. The simplest way to perform interprocess communication, because ```Messanger``` queues all requests into a single thread. So your service is automatically thread-safe in that way. 
3. Using AIDL 
    - Android Interface Definition Language (AIDL) decomposes objects into primitives that the operationg system can understand and marshals them across processes to perform IPC. ```Messanger``` is an abstraction above AIDL. If your app needs to handle multiple requests simultaneously, then you can use AIDL directly. You have to make application thread-safe yourself.

### Write an example of extending binder class
1. This will work only if client and a service are in the same process and application
2. In service create an instance of ```Binder``` that does one of the following 
    - Contains public methods that the client can call 
    - Returns the current ```Service``` instance, which has public methods the client can call
    - Returns an instance of another class hosted by the service with public methods the client can call 
3. Return this instance of ```Binder``` from the ```onBind()``` callback mthod
4. In the client, receive the ```Bindуr``` from the ```onServiceConnected()``` callback method and make calls to the bound service using the methods provided

### How to use a ```Messanger``` class?
1. The service implements a ```Handler``` that receives a callback for each call from a client
2. The service uses the ```Handler``` to create a ```Messenger``` object (which is a reference to the ```Handler```)The ```Messenger``` creates an```IBinder``` that the service returns to clients from ```onBind()```
3. Clients use the ```Ibinder``` to instantiate the ```Messenger``` (that references the service's ```Handler```) which the clent uses to send ```Message``` objects to the ervice
4. Teh service receives each ```Message``` in its ```Handler``` specifically in the ```handleMessage()``` method 

### How do we get Binder interface?
bindService() returns Immediately so we have to use ```ServiceConnection``` with callbacks

### Write example of binding service on paper

### What if bindService() returns false? 
Client does not have a valid connection to the service. Still you should call ```unbindService()``` otherwise client will keep the service from shutting doen when it is idle

### Any notes for binded services? 
- Trap ```DeadObjectException``` which are thrown when the connection has broken
- Objects are reference counted across processes
- You usually pair the binding and unbinding during matching bring-up and tear-down moments of the client's lifecycle

### What is bad in starting and stopping bind service in ```onResume()``` and ```onPause()```? 
This callbacks are called at every lifecycle transition, so it will be called to frequenty. 

### Draw bounded services lifecycle
![](https://i.imgur.com/zbi2ySi.png)

### How to create both bound and start service?
Implement both ```onStartCommand()``` and ```onBind()```. In this case if all clients are unbound the service is not stopped. It has to stop explicitly by calling ```stopSelf()``` or ```stopService()```.
 
### How to create foreground service? 
Use ```startForegroundService()``` with intent and the service has to call ```startForeground()``` withing five seconds. 
1. Request the foreground service permission in the manifest. It is normal permission so the system automatically grants it to the requesting app.
2. Call ```startForeground()``` in the service class. Within 5 second since the ```startForegroundService()``` was called, so you better to do it in the ```onCreate()``` method. This method takes two parameters: a positive integer that uniquely identifies the notification in the status bar and the Notification object itself. 
3. Create notification and Notification channel in order to display a must-have notification
4. Call ```stopForeground()``` somewhere. Notice that the service continue running
5. Call ```stopSelf()``` somewhere 

### How to communicate with started service? 
The started service can create a ```PendingIntent``` for a broadcast (with ```getBroadcast()```) and deliver it to the service in the ```Intent``` that starts the service. The service will use the broadcast to deliver a result.

### If we send 3 ```startService()``` with ```Intent``` how many times do we have to call ```stopSelf()``` or ```stopService()```?
Only one

### How to avoid the case when you have several pending intents, but you want to call ```stopSelf()``` within the service? You will abort all future intents without even knowing.
In ```onStartCommand()``` the method ```stopSelf(int)``` should be called with int in arguments. This int is a start request ID. If you have another intent the ID will not match.

### How to create a bounded service (maybe implement an example service on paper)
1. Implement ```onBind()``` callback to return an ```IBinder``` that defines the interface for communication with the service. Other application components can then call ```bindService()``` to retrieve interface and begin calling methods on the service. 
2. Call ```bindService()``` to retrieve an interface for the service. Provide an implementation of ```ServiceConnection``` which monitors the connection with the service. The return value will indicate if the service exists and whether the client is permitted access to it. Android will call ```onServiceConnected()``` in ```ServiceConnection``` in success case. ```onServiceConnected()``` method includes an ```IBinder``` argument which the client then uses to communicate with the bound service. 
3. Implement interface as an implementation of ```IBinder``` 
4. Call ```unvindService()``` from client of the service when te work is done

### How many times the IBinder will be created for several clients of the service?
Only one. The system caches the IBinder result that was return on the first call of ```onBind()``` and then uses it for the next calls without calling ```onBind()``` again. 

### Explain main callback methods of the service

#### onStartCommand()
System calls it after ```startService()```. When the system is started it can run indefinetely. It is responsibility of the service to stop itself after the work is complete by calling ```stopSelf()``` or ```stopService```
If the service is *bounded* service do not implement this method
#### onBind()
System calls this method after calling ```bindService()```. To communicate with the service you must provide an interface that clients use by returning an ```IBinder```. **ALWAYS** implement this method even if you are creating only-starting service. 
#### onCreate()
One time setup procedure when the service is created (before ```onStartCommand()``` or ```onBind()```)
#### onDestroy()
System calls this method when the service is no longer use and is being destroyed. Clean up resources such as threads, listeners or receivers. The last call that the service receives. 

### When Android kills service
The system kills service only if the memory is low and it must recover system resources for the activity that is in the user focus. If the service is bounded to that activity it is less likely to be killed. If the service is running in the foreground it's rarely killed. If the service is long-running and *started* the system lowers its position in the background tasks over time and it is more and more likely to be killed. You must design the service the way that it may be restarted grecafully by the system. The system will restart the service as soon as resources are available. Also it depends on the value that you return from ```onStartCommand()```

### Which are the required attributes of the service declaration in the manifest?
```android:name``` is the only required attribute. 

### Can you change the name of the service after you publish your application? 
You can but don't do it!

### What is the deal with implicit intent and Service?
Don't use implicit intent and intent-filters for services. It is a security hazard because you cannot be certain of the service that responds to the intent, and the user cannot see which service starts. From api 21 the system will throw an exception if you call ```bindService()``` with an implicit intent!

### Draw and explain lifecycle of the service
![](https://i.imgur.com/vuSGGT0.png)
You can also bind to a service that is already started with ```startService()```

### State all lifecycle methods
- onCreate()
- onStartCommand()
- onBind()
- onUnbind()
- onRebind()
- onDestroy()

### When onRebind() is called?
When the unbindService() was already called on that service.

### Do we have to call the super.smth() in the overriden methods. 
No

### What is entire lifetime of a service? 
Between the time that ```onCreate()``` is called and the time that ```onDestroy()``` retruns. 

### What is active lifetime of a service?
Begins with a call to either ```onStartCommand()``` or ```onBind()```. For started service the lifetime ends when its entire lifetime ends. For bounded services the lifetime ends when ```onUnbind()``` returns.

## Permissions

### What types of permission exists? 
- Install-time permissions - Limited access to restricted data and actions 
    - Normal Permissions - data beyond app's sandbox. But this data present very little rist to the user's privacy and the operation of other apps. 
    - Signature Permissions - if two apps has the same sign certificate and one of them has signature permission then the other app will have access at install time 
- Runtime permissions (dangerous permissions) - request those permissions at runtime. For more private user data 
- Special permissions - correspond to particular app operations. Only the platform and OEMs can define special permissions. Special app access page in settings mostly contains such permissions


### If library has some permission will you have it too? 
Yes 

## Motion Layout 
:::spoiler Question
#### What is changing when the one specifies the type of ```keyPosition```
The coordinate system changes. How x and y are calculated 

#### What is the magic behind the CustomAttribute?
The Motion Layout using reflexion will find the function and call it repeatedly 

#### What might be the problem with onSwipe?
Sometimes the direction might be selected wrongly 
https://codelabs.developers.google.com/codelabs/motion-layout/#9
``` xml 
<OnSwipe
       motion:touchAnchorId="@id/moon"
       motion:touchAnchorSide="bottom"
/>
```
To avoid bugs like this, it is important to always choose a touchAnchorId and touchAnchorSide that always progresses in one direction throughout the duration of the entire animation.

In some animations, no view has an appropriate touchAnchorSide.

This may happen if every side follows a complex path through the motion, or views resize in ways that would cause surprising animations. In these situations, consider adding an invisible view that follows a simpler path to track.
:::

## Data Store
:::spoiler Questions
#### What is DataStore?
It is a library that is a part of Jetpack. It is a replacement for a Shared Preferences. 

#### Why it is better then Shared Preferences? 
Shared Preferences has a lot of drawbacks. It works in a UI thread while performing disk IO operation which is very time consuming. It also throws parsing errors as a Runtime Exception. 

![](https://i.imgur.com/cNiR5Dd.png)


#### Describe DataStore

There are two different data stores available: 

- Preference DataStore - key value
- Proto DataStore - typed objects 
:::

### Constraint layout vs relative layout 
Что заменяет 
Что улучшает 

### Плюсы и минусы constraint layout 

### Hot vs Cold stream 

### Why Android uses VM
There are many reason that Google engineers decide to use Android with VM, but two main reason is:
Security: In theory, app code is totally isolated by the VM and cannot even “see” the host OS. So app code that contains malware cannot affect system directly, make app and system more robust and reliable.
Platform independent: Android platform can run on different devices with different architectures (ARM, MIPs, x86). To abstract out the need to compile binaries for each architecture, VM comes into play.

### JVM vs DVM

![](https://i.imgur.com/RzIgUvd.png)

### Register based vs Stack based

Stack based VM uses stack to access operands. LIFO principle. Good example JVM. To add 
``` ASM
POP 
POP
ADD
PUSH
```

Register based VM uses registers of processor to store operands. As array
To add
``` ASM 
ADD R1, R2, R3
```
Faster because only one command and we can "cache" results of some commands
Larger commands


### Describe Dalvik
- Uses 16 bit instructions (unlike javas 8 bit)
- Register based 
- Each app in its own process and each process is in its own VM
- Registers are 4 bit fields

![](https://i.imgur.com/Gr5ePMf.png)

BSD socket listens to all income requests 
When the request for new DVM got, the system forks the instance of Parent DVM and gives it to the child. 

### What is Looper? 

## Notifications


## What is Play Feature Delivery?
It allows user to download only required modules for their needs. Or to configure each apk for specific device

---
#### Futher reading 
1. GC DEBUG: https://source.android.com/devices/tech/dalvik/gc-debug
2. https://developer.android.com/guide/components/foreground-services#kotlin Про restrictions 

---
#### Resources
1. https://www.javatpoint.com/android-interview-questions
2. https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment
3. https://medium.com/hootsuite-engineering/handling-orientation-changes-on-android-41a6b62cb43f
4. https://programming.vip/docs/the-best-solution-for-android-screen-rotation-processing.html
5. https://github.com/MindorksOpenSource/android-interview-questions#data-structures-and-algorithms
6. https://blog.mindorks.com/a-complete-guide-to-learn-rxjava-b55c0cea3631
7. https://www.toptal.com/android/interview-questions
8. https://android.jlelse.eu/i-had-10-android-interviews-during-the-last-two-years-heres-the-questions-plus-some-lessons-i-ve-cdc583dfbc65
9. https://medium.com/android-news/virtual-machine-in-android-everything-you-need-to-know-9ec695f7313b

