Skip to content

Instantly share code, notes, and snippets.

@sagarnayak
Last active June 24, 2022 23:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagarnayak/119308c2755a42acf763b3168a3d2756 to your computer and use it in GitHub Desktop.
Save sagarnayak/119308c2755a42acf763b3168a3d2756 to your computer and use it in GitHub Desktop.
android interview questions

Android Interview Questions

OOP Concepts

Object-Oriented Programming is a methodology of designing a program using classes, objects, inheritance, polymorphism, abstraction, and encapsulation.

Access modifiers

  1. Private - can be accessed only in class
  2. Public - can be accessed outside of class
  3. Protected - can be accessed in derived class

Inheritance

Single, multilevel, hierarchial

multiple inheritances are not allowed in java. inheritance is done by extending with extends keyword.

How string class is implemented in java, and why this is immutable ?

The string is not a primitive data type in java. this is just a wrapper around an array of characters. so when we define a string in java this is allocated a specified space as per requirement. and when this is changed the whole memory space changes. the previous object is not changed.

What is difference?

String str = "abc";
String strTwo = "abc";
String strObject = new String("abc");
String strObjectTwo= new String("abcdefghijk");
  • in case for str and strTwo both will call the intern() method in the String object and will point to the same abc value in the String pool in the heap memory.
  • but when we create a new object of String a entirely new object is created in heap memory.
  • the == operator will give you a true in case of str and strTwo comparison but this will not give true for str and strObject. Reference

Difference between Integer and int.

Integer is a wrapper around the premitive int. int is the premitive data typf of java.

String Vs StringBuilder Vs StringBuffer

String is not mutable. StringBuilder is mutable and not thread safe. StringBuffer is not mutable and thread safe.

Arraylist and Vector

  • Vector is synchronized, means that if you are using the same vector among multiple threads it will synchronize the values among the threads.
  • ArrayList is not synchronized.
  • If more space is required then ArrayList increases its size by 50% whereas vector doubles its size.

Difference between Abstract class and Interface

  • An abstract class can contain concrete method as well as method definition, but an interface can only contain method definitions without the body.
  • Abstract class methods can have any modifier but the interface can only have public modifier which is predefined.
  • An abstract class can have any kind of member variable but the interface can only have public static final variables which is defined by default.
  • we can not instantiate any of abstract class or interface.

Difference between HashSet and TreeSet and LinkedHashSet

  • All store hashmaps internally, so all the elements are unique. no duplicates are saved.
  • HashSet does not guarantee any order and sorting.
  • Linked HashSet has ordered data according to the insertion.
  • treeset saves the data sorted alphabetically.

Serilizable Vs Parcelable

  • Serializable is java class to transfer data by converting it to a format which can be stored and retrieved later.
  • Parcelable is an android native class to do the same work.
  • generally, parcellable is considered faster then serializable.

Final, Finally, Finialize

  • final is used to declare constant fields in java.
  • finally is used to indicate a block of code to run after try and catch block.
  • finalize is a function invoked at the time of garbage collection in java.

Method Overloading and Method Overriding

Overloading

  • both are forms of polymorphism in OOP. method overloading is the concept of using multiple methods with the same name but a different number of parameters or different parameters.
  • the return type of a method does not count as a criterion for polymorphism.
  • method overloading is done at compile time.
  • static methods can be overloaded.

Overriding

  • defining the method definition for a parent class method in the child class is called method overriding.
  • this is done at runtime.
  • private and final methods can not be overridden because they are not scoped outside of class.

Activity and activity lifecycle

An Activity is the screen representation of an application in Android.

It serves as an entry point for the user’s interaction. Each activity has a layout file where you can place your UI. An application can have different activities. For example, facebook start page where you enter your email/phone and password to login acts as an activity.

Methods in activity lifecycle -

onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy() onRestart() is called when activity is at the onStop() and it is opened. onSaveInstanceState() and onRestoreInstanceState() are called when the system initiate a process kill. this is used to save the state of the activity. Saving UI state

Fragment and Fragment lifecycle

The fragment is a modular section of activity with its lifecycle methods and which can be reused at different places as per the requirement. a fragment can not be used as a stand-alone from other UI elements. it has to be used inside an activity.

Lifecycle methods -

onAttach(), onCreate(), onCreateView(), onStart(), onResume(), onPause(), onStop(), onDestroy(), onDetach()

Order of lifecycle method calling in activity and fragment

Activity Start and back pressed

for tables below Activity 1 has Fragment 1 and Activity 2 has Fragment 2.

Activity Fragment
onCreate()
onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart()
onStart(), onResume()
onResume()
back Pressed
onPause()
onPause()
onStop()
onStop()
onDestroyView(), onDestroy(), onDetach()
onDestroy()

Navigation in 2 Activities

Activity 1 Fragment 1 Activity 2 Fragment 2
Start Activity 1
onCreate()
onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart()
onStart(), onResume()
onResume()
Start Activity 2
onPause()
onPause()
onCreate()
onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart()
onStart(), onResume()
onResume()
saveInstanceState()
saveInstanceState()
onStop()
onStop()
Back Pressed Activity 2
onPause()
onPause()
onStart()
onStart(), onResume()
onResume()
onStop()
onStop()
onDestroyView(), onDestroy(), onDetach()
onDestroy()
Rotate Device
onPause()
onPause()
saveInstanceState()
saveInstanceState()
onStop()
onStop()
onDestroyView(), onDestroy(), onDetach()
onDestroy()
onAttach(), onCreate(B)
onCreate(B)
onCreateView(B), onActivityCreated(B), onStart()
onStart(), onRestoreInstanceState(B), onResume()
onResume()

Device Roration with multiple Activities

Activity 2 is started and in resume, Device now in portrait

Activity 1 Fragment 1 Activity 2 Fragment 2
Rotate Device
onPause()
onPause()
saveInstanceState()
saveInstanceState()
onStop()
onStop()
onDestroyView(), onDestroy(), onDetach()
onDestroy()
onAttach(), onCreate(B)
onCreate(B)
onCreateView(B), onActivityStarted(B), onStart()
onStart(), onRestoreInstanceState(B), onResume()
onResume()
Device now in landscape
back pressed
onPause()
onPause()
onDestroyView(), onDestroy(), onDetach()
onDestroy()
onAttach(), onCreate(B)
onCreate(B)
onCreateView(B), onActivityCreated(B), onStart()
onStart(), onRestoreInstanceState(B), onResume()
onResume()
onStop()
onStop()
onDestroyView(), onDestroy(), onDetach()
onDestroy()

Here the destroy process for activity 1 is being performed when back pressed. this is because the original state for activity 1 is portrait. but the current orientation of device is landscape. therefore destroy is being done. In case we have again rotated the device to portraint in activity 2 and pressed back this will not perform the destroy in the activity 1, and it will start from the onStart().

Process kill by the Android in background

Assume Activity 2 is in onResume(), activity 1 is in stop()

Activity 1 Fragment 1 Activity 2 Fragment 2
Press Home
onPause()
onPause()
saveInstanceState()
saveInstanceState()
onStop()
onStop()
App goes to background
Android kills the process
User open the app
onAttach(), onCreate(B)
onCreate(B)
onCreateView(B), onActivityCreated(B), onStart()
onStart(), onRestoreInstanceState(B), onResume()
onResume()
Back Pressed
onPause()
onPause()
onAttach(), onCreate(B)
onCreate(B)
onCreateView(B), onActivityCreated(B), onStart()
onStart(), onRestoreInstanceState(B), onResume()
onResume()
onStop()
onStop()
onDestroyView(), onDestroy(), onDetach()
onDestroy()

Points to remember in lifecycle method calls

  • all lifecyle process originates from the fragment except the first time creation and resume process.
  • onRestoreInstanceState() is not available for fragment.
  • bundle is available for activity in onCreate() and onRestoreInstanceState().
  • bundle is available for fragment in onCreate(), onCreateView(), onActivityCreated().
  • if fragment instance is once created the lifecycle method calling is changed and the previous instance is reused for the fragment. onAttach(), and onCreate() for fragment are called before activity onCreate().

Handle back press in fragment

  • get getSupportFragmentManager() and beginTransaction()
  • add the new fragment to back stack by addToBackStack()
  • commit the transaction.
  • on back press of activity we can get the number of fragments in backstack by calling getSupportFragmentManager().getBackStackEntryCount() and decide weather to consider that back press is for activity or fragment.
  • to pop out a fragment from backStack call getSupportFragmentManager().popBackStack()
  • if that back is considered for the activity then call super.onBackPressed()

Why default constructor is mandatory in fragment

this is done to retain state for the fragment. if in any case the fragment is destroyed by system the same bundle will be delivered to that fragment while re-starting it.

Communication with other fragments

As fragment is designed to be robust and should be reused at any place. we should keep it independent of other dependency. any data required from fragment should be through method call from container activity and any data required into fragment should be through a callback to container activity.

Service

  • Service is a component of android which is used to perform task in background.
  • it does not provide any UI.
  • it can be used to perform any task like play music or any long running network operation.

Types of Service

  • Foreground - service which has a notification running on the foreground to notify about the statsus of the task.
  • Background - service which runs on background and does user an not directly have any connection to it.
  • Bound - this is kind of service which runs on AIDL with a client and server interface within two different android application.

Start Service

we can start any service by calling startService() or binding to it by bindService().

intent service and Service

  • we can create service in 2 ways, extending Service or extending IntentService.
  • service once started runs on the main thread but in background.
  • upon task completion we can either stop the service or it can call stopSelf().
  • IntentService can get the task done and after the task is completed it will stop itself.
  • it runs task on another thread then the main thread.

Communication in srvice

  • to get data from service about any update or status we should use broadcast.

Job Scheduler

This is a mechanism by android through which all process register for their background service to be done with the criteria required and it is executed by android in batch to optimize battery and performance of device.

  1. To create a job extend the job service define your work in the callback methods.
  2. callbacks are onStartJob() and onStopJob()
  3. return true from onStopJob() if you want to reschedule it and false otherwise.
  4. call jobFinished() if you have completed the task.
  5. define your job scheduler in manifest.
  6. get job scheduler service and schedule the task.

Broadcast receiver

This is a component in android which is used to propagate data and information system wide. to receive it it has to be registered with an intent filter in manifest or at run time.

Intent

Intent is used to send data from one component to another. this is used to pass data between Activity, Services, Broadcasts.

Types

  1. Explicit - where destination is defined. like starting an activity.
  2. Implicit - where destination is not defined like sharing a content or making a call to a number.

Pending Intent

this is a data packet which is not delivered immediately and generally executed at somepoint in future.

IntentFilter

This is a structured description to the target intent to look for. this can be used in broadcast receiver to listen for a specific intent broadcast.

Threading

  • to perform cpu intensive task in other thread java has 2 ways -
  1. extend Thread class
  2. implement the Runnable interface
  • but these components have their own limitations. if we want to perform two task then we need to create two instances of these. and like wise for each further task. this instances have a memory overhead on the storage and we have a limitation to that.
  • so we need a better solution to this. and android has Looper, Handler and message queue architecture for that. handler is responsible for placing the runnable task to the message queue and looper will loop through it and execute defined task with the help of handler.

ANR

Activity not responding. this happens when no frame is generated for 5 seconds.

AIDL

Android Interface Definition Language This is the way through which two android application can act as client and server and one app can access service of another application through binding to that service.

AsyncTask and problem

AsyncTask lifecycle does not depend on activity and if it has activity reference it may create a null pointer if UI is updated after task completed and Activity is not running or Activity instance changed due to configuration change.

DVM and .dex

  • dvm is Delvik Virtual Machine which runs the andriod apps and seperate processes and provide a sandbox to each of them to execute threir task.
  • the file formar which is handled by DVM is .dex and the package is .apk

FlatBuffer

This is a serilization library which is created by google for data communication in games. this is a very memory effecient and fast serilization library.

AAPT

Android Assets Packaging Tool This is the base builder of android applications. it converts all the code and assets into a runnable file.

DDMS

Delvik Debug Monitor Server

ADB

Android Debug Bridge Command line tool to debgug android app.

ART and DVM

  • Delvik Virtual Machine is the runtime used to convert dex files to machine code during app execution in android 4.4.
  • Android RunTime is the new runtime which is introduced in android 5.0 to take care of the same task.
  • the adventage with ART is that it works on Ahead of time compilation, so that programs runs faster and startup time is reduced. in the otherhand DVM is Just in Time runtime environment.
  • Medium Article
  • Android Doc

HEAP and Stack memory

Stack memory is used to store data types, function calls and reference to variables. Heap memory is created for each class object created.

Reference

CPU Architecture

  • ARMV7 - optimised for batter consumption.
  • ARM64 - used for 64bit processing
  • ARMx86 - most powerful of rest two but less battery effecient and used very less.

Launch Mode

  • STANDARD - this is the default launch mode.
  • SINGLE_TOP - here only one instance for the activity is at top. if started again and not in top it will create another instance but if in top it will just bring that to front and don't start a new one.
  • SINGLE_TASK - new process is created fro this activity if instance not exist in a new process. if already exist kill others above it and bring to top.
  • SINGLE_INSTANCE - new process is started for this activity and no other activity can exist for this process.

TaskAffinity is a factor due to which the new process is not created as new process in android device. by default all activity has the same affinity. This applies to singletask and single instance.

Launch Flag

  • FLAG_ACTIVITY_SINGLE_TOP - similar to single_top
  • FLAG_ACTIVITY_NEW_TASK - similar to single task
  • FLAG_ACTIVITY_CLEAR_TOP - used along with FLAG_ACTIVITY_NEW_TASK to clear the top activities

Permission Levels

  1. Normal
  2. Dangerous
  3. Signature
  4. SignatureOrSystem

Commit and Apply in SharedPreference

commit is synchronous and apply is not.

Recyclerview and List view difference

it use already created views to populate the data through onBindViewHolder() so the time to create view is saved in reycclerview.

Version Name and Version Code

version name is only to show to the user about the app version. it can be a decimal value. Version code has to be a number and this is detected by google play store while updating your app.

MVVM

This is the design pattern which can be used to create android application.

  • there are 3 components involved here -
  1. Repository
  2. ViewModel
  3. View (Activity)
  • Repository is responsible for the management of all the business logic. If there is any data required or posting of data is required then respository is responsible for it.
  • ViewModel is responsible for getting the required data from repository for its view. it is used for persistance of data during the configuration change.
  • View, which is activity in our case is just the view which propegates any user action to the repository through viewmodel. and perform any event received from viewmodel.

LiveData

  • This is a android architecture component that allow us to propegate data to the observer in an observable pattern.
  • the adventage with livedata is that it is lifecycle aware. so if the observing component is not in foreground it will not send the update.
  • the livedata components we use in android are generally MutableLivedata and MediatorLiveData.

ViewModel and saveInstanceState()

  • these are the mechanism which is used to save data of the UI state in case activity is destroyed.
  • the ViewModel is used to save the data which can survive the configuration changes like rotating the device.
  • but this can not survive the destruction of an activity if the activity is destroyed in background by the android OS due to low on memory.
  • in this case we need to use the saveInstanceState() and restoreInstanceState().
  • onSaveInstanceState() has a limited memory to store the parceable data for the UI, on the other hand ViewModel has to limit for it and it can store any data as required.

Dependency Injection

This is a programming practice through which any required instance of any class or utility is provided to the required place. Here the dependency creation code is encapsulated away from the rest of the code into the dependency injection modules, and makes the initialisation and for the global dependencies one time and easy to organise.

in case of Dagger -

  • it has modules which have methods with @provides annotation which provides any dependency.
  • those modules are added into subcomponents for the purpose and subcomponents are added to AppComponent.
  • this dependency graph helps the dependency injection framework to locate the required dependency and deliver it to the required place.

Notification

Notification provides short information to user even if the app is not open.

This has many templates for the developer to use at different use case. some of them are direct reply and notification with action buttons etc.

To show a notification create the notification object and pass this to the notification manager.

Notification Channel

  • This is a new feature added for the android OREO
  • through this feature each notification that we post are from some channel. user can customise the channel settings like blocking it or disabling sound for that channel.
  • channel are created based on the user use case, like message channel, app announcement etc.

Android Version and Fatures

Android 11

  • 5G support.
  • privacy improvements.
  • chat bubbles.

Android 10

  • this has support for the biometric auhtentication for user with fallback to pin or pattern lock.
  • TSL 1.3 support.
  • building apps for foldable android devices.
  • dark theme.
  • bubble to perform multitask from any place of the application.
  • 5G support.

Android Pie, 9

  • indoor positioning
  • phones with notches into the display area may block the content of the window. in pie we can get the display area that is within cutouts and adjust our layout accordingly.
  • multi camera support.

Android OREO, 8

  • Picture in picture mode
  • android notification channel
  • android notification dots amd badges
  • downloadable font and and resizable textview
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment