Android Interview Material
Ans:- Retrofit is a REST client for Android, through which you can make easy to use interfaces which can turn any Android app into a powerful one. Retrofit is developed by Square Inc. Retrofit turns your REST API into a Java interface. Retrofit can perform Async and sync requests with automatic JSON parsing without any effort.
Q2] What is Volley?
Ans:- Volley is a networking library it offers great features like synchronous requests, asynchronous requests, prioritization, making multiple requests at the same time, ordered requests, and of course caching.
Q3] Difference between retrofit and volley?
Retrofit | Volley |
---|---|
Retrofit can parse many other types of responses automatically like: |
StringRequest – This type of request converts the response into a String. |
Retrofit does not support caching. |
Caching: Android volley has a flexible caching mechanism. When a request is made through volley first the cache is checked for an appropriate response if it is found there than it is returned and parsed else network hit is made. |
Retrofit does not support any retrying mechanism. But it can be achieved manually by doing some extra code. |
Retrying Mechanism With volley, we can set a retry policy using the setRetryPolicy method. It supports the customized request timeout, number of retries, and backoff multiplier. |
On the other hand, Retrofit has full support for Post Requests and Multipart uploads. |
Post Requests and Multipart Uploads: Volley supports both posts requests and multipart uploads but for post requests, we have to convert our java objects to JSONObject. Also for multipart uploads, we have to do some extra code and use some additional classes |
4] Difference between list view and
recycler view?
RecyclerView
|
ListView
|
Yes, RecyclerView requires an additional dependency |
No, available natively |
Mandatory ViewHolder pattern providing better performance |
ViewHolder pattern can be supported with customisation |
Advanced Layout Management capabilities for vertical and
horizontal lists, grids and staggered grids |
Vertical list only |
Supports notifications if the entire data set has changed, item
gets added, item gets removed or item gets changed |
Supports notifications if the entire data set has changed |
Dividers between items not shown by default. Use ItemDecorations
to add margin and draw on or under an Item View. |
Dividers between items shown by default. Item decoration
requires customisation for ListView. |
ItemAnimator makes it easy to add animations |
Very complex to implement |
5] What are the different threads in
android?
- AsyncTask: Helps get work on/off the UI thread
- HandlerThread: Thread for callbacks
- ThreadPoolExecutor: Running lots of parallel work
- IntentService: Helps get intents off the UI thread
6]
Difference between MVP and MVVM?
MVP
(Model-View-Presenter) |
MVVM (Model-View
-ViewModel) |
In MVP we have Tight coupling between View and Presenter. |
In MVVM
No tight coupling between the view and viewmodel. |
MVP
have one to one relation between view and presenter. |
MVVM
have one to many relation between view and viewmodel. |
In MVP
The Presenter has knowledge about the View. |
In MVVM
ViewModel do not have reference of the View. |
MVP is
ideal for simple and complex applications. |
MVVM is
not ideal for small scale projects. |
In mvp
we use large amount of interfaces for interaction between layers. |
In MVVM
No interfaces between view and model. we have to create observables for each
UI component. |
In MVP
code size is quite Large |
In MVVM
code size is less. |
In MVP
Presenter need to check if view is still alive when invoking methods. |
In MVVM
LiveData Solves issue if view is alive. |
In MVP
Easy to carry out Unit testing but a tight bond of View and Presenter makes
it slightly difficult |
In MVVM
Easy to do unit testing. |
7] How
MVVM works ?
MVVM stands
for model view -viewmodel
The view means activity or fragment
is only responsible for what is visible on view and dose not know anything
about the model, it only displays data.
The view-model only exposes data to
the view, it doesn’t care where the data comes from.
The model is only concerned with
data. We don’t have any functions that format the data for the help of the view
7.1] LiveData:
LiveData is an observable data holder
class, and it is Lifecycle aware component. it means, it respects the lifecycle
of other app components
like activities, fragments, and
services. we can say that LiveData is only updates app component observers that
are in an active lifecycle state.
The advantages of using LiveData.
-we dont have memory leaks
-We dont get crashes due to stopped
activities
-we always get updated data
-If an activity or fragment is
recreated due to a configuration change, like device rotation, it immediately
receives the latest available data.
7.2]
livedata/Mutable livedata: postValue/setValue
When we don’t want to modified our
data, at that time we use LiveData. If we want to modify our data later we use
MutableLiveData.
-we can update value using setValue()
and postValue()method //getuser().setValue(userObject) or
getuser().postValue(userObject)
=While using main thread to update the
data we can use setValue() method of MutableLiveData Class, and When using
background thread to update
the LiveData we use PostValue() method
of MutableLiveData.
7.3]
ViewModel use:
ViewModel is a class which is responsible
for preparing and managing the data for view like Activity and Fragment.
It also handles the
communication of the Activity / Fragment with the rest of the application.
The ViewModel class allows data
to survive configuration changes such as screen rotations.
ViewModel objects are
automatically retained during configuration changes so that data they hold is
immediately available to the next
activity or fragment instance.
advantages of using ViewModel
-it Handle configuration changes:
-Lifecycle Awareness: They are
automatically cleared when the Lifecycle they are observing gets permanently
destroyed.
-Data Sharing: Data can be easily
shared between fragments in an activity using ViewModels
//Kotlin-Coroutines support
8] What is a
ViewBinding?
View binding allows us to
more easily write code that interacts with views. Once view binding is enabled
in a module, it generates a binding class for each XML layout file present in
that module. An instance of a binding class contains direct references to all
views that have an ID in the corresponding layout.
The Data Binding Library is
a support library that allows you to bind UI components in your layouts to data
sources in your app using a declarative format rather than programmatically.
Differences View Binding and
Data Binding
1. View Binding library is faster than Data Binding
library as it is not utilising annotation processors underneath, and when it
comes to compile time speed View Binding is more efficient.
2. The one and only function of View Binding is to bind
the views in the code. While Data Binding offers some more options like Binding
Expressions, which allows us to write expressions the connect variables to the
views in the layout.
3. Data Binding library works with Observable Data
objects, you don't have to worry about refreshing the UI when underlying data
changes.
4. Data Binding library provides us with Binding
Adapters.
5. Data Binding library provides us with Two way Data
Binding, this is a technique of binding your objects to xml layouts, so that
both object and layout can send data to each other.
AppCompatActivity provides native ActionBar support that is
consistent across the application. Also, it provides backward compatibility for
other material design components till SDK version 7(ActionBar was natively
available since SDK 11). Extending an Activity doesn’t provide any of these.
Note: Since SDK 21 every activity by default, extends AppCompatActivity.
Activity is the base class. FragmentActivity extends Activity.
AppCompatActivity extends FragmentActivity. ActionBarActivity extends
AppCompatActivity. FragmentActivity is used for fragments. Since the build
version 22.1.0 of the support library, ActionBarActivity is deprecated. It was
the base class of appcompat-v7
. At present, AppCompatActivity is the base class of the support
library. It has come up with many new features like ToolBar, tinted widgets,
material design color pallets etc.
The android platform supports a wide variety of the versions and
devices to choose from. With the release of every new version, new Android APIs
are added and evolved. To make these new Android APIs available to users on
older devices the Android Support Library was designed. Android Support Library
provides developers with newer APIs that are compatible on older framework releases.
Android
Support Library is not just a single library. It’s a collection of libraries
that have different naming conventions and usages. On a higher level, it’s
divided into three types;
- Compatibility Libraries: These focus on back porting
features so that older frameworks can take advantage of newer releases.
The major libraries include
v4
andv7-appcompat
. v4 includes classes like DrawerLayout and ViewPager while appcompat-v7 provides classes for support ActionBar and ToolBar. - Component Libraries: These include libraries of
certain modules that don’t depend on other support library dependencies.
They can be easily added or removed. Examples include
v7-recyclerview
andv7-cardview
. - Miscellaneous libraries: The Android support libraries
consists of few other libraries such as
v8
which provides support for RenderScript,annotations
for supporting annotations like @NonNull.
onCreate()
is the first method that’s invoked when an activity is launched for the first
time. onStart() is invoked after onCreate() has completed it’s task. onResume()
is called after onStart() has completed. When an activity leaves its foreground
(probably for a smaller duration such as standby/sleep) onPause() is invoked
followed by onStop()(when the activity is not visible. eg. some other
application is launched). onDestroy() is called when the activity or
application is killed. Essentially the lifecycle methods are divided into three
layers of duration :
- onCreate() and onDestroy() are
present during the entire duration of the activity
- onStart() and onStop() are
present while the activity is visible
- onResume() and onPause() are
present while the activity is in foreground
When the screen is rotated, the current instance of the activity
is destroyed a new instance of the Activity is created in the new orientation.
The onRestart() method is invoked first when a screen is rotated. The other
lifecycle methods get invoked in the similar flow as they were when the
activity was first created.
In general the onSaveInstanceState() is invoked after
onPause() and before the onStop(). But the API documentation explicitly states
that the onSaveInstanceState( ) method will be called before onStop() but makes
no guarantees it will be called before or after onPause(). The
onRestoreInstanceState() is called after onStart() is invoked. The
onRestoreInstanceState() method is invoked only when the activity was killed
before. If the activity is NOT killed the onSaveInstanceState() is NOT called.
When the activity is being destroyed, the onSaveInstanceState() gets invoked.
The onSaveInstanceState contains a Bundle parameter. The data to be saved is
stored in the bundle object in the form of a HashMap. The bundle object is like
a custom HashMap object. The data is retrieved in the onRestoreInstanceState()
method using the keys.
17] Activity
LifeCycle?
18] Fragment
LifeCycle?
1] Features
of kotlin.
Kotlin provides many powerful features
over Java like.
-Concise code:: Every developers love
clean and concise code. Less code takes less time to write, less time to read,
it have less bugs and
also makes easy to maintain it.
-Null safety:: More than 70% android
app crashes due to null pointer exception of java. But Kotlin handles nulls
pointer exception really nicely.
In Kotlin we cannot get null pointer
exception implicitly.
-Expressive code:: Kotlin is really
expressive. All data types, built-in functions, keywords, are very expressive
and easily understandable.
Kotlin is designed in such a way so
that even a person who never codes in kotlin can easily understand its code.
-Interoperability with Java: Kotlin is
100% interoperable with java. You can easily call Kotlin code from Java and
Java code from Kotlin.
-Modern features:: in kotlin they
introduces a lot of new features like Lambda functions, smart casts, null
safety, operator overloading.
Which will help in increasing
productivity.
2] Kotlin vs
java
-Kotlin is null safe lang
-Kotlin have extension function
-Data classes
-Type Inference:Kotlin we dont need
to specify the type, of each varaible explicity base on assignemnt.
-Kotlin allows writing less code
-It solves developer challenges
-Adopting Kotlin is easy
-Kotlin is fully compatible with Java
- When we call the Kotlin code from the Java we use jvmstatic, jvmoverloads, jvmField.
-jvmStatic: the package-level functions are represented as static methods. Also, in Kotlin, we can make static methods for functions that are
defined in some companion object or named object by using the @JvmStatic annotation. From java we can call that method without INSTANCE keyword.
We direclty call classname dot variable.
-JvmOverloads: to use the default value, we can use the @JvmOverloads annotation. Now, after using the annotation , calling from Java,
we do not need to pass all the parameters.
-JvmField: if you want a particular field to be used as a normal field and not as getter or setter then we have to tell the compiler not to
generate any getter and setter for the same and this can be done by using the @JvmField annotation.
4] == &
=== Difference: ==(Structural) && === Referecial
== operator is used to compare the
data of two variables.
=== operator is used to compare the
reference of two variable or object.
5] Difference
between const val
const and val both imutable. val
variable is initialized at runtime and const initialized at compile time
lateinit
and Lazy
The lateinit keyword is used for late
initialization of variables. it can be use with var not val. When we initilize
the value, need to check is that initilized or not. //we can chcek
if(this::courseName.isInitialized)
we use Lazy mainly when we want to
access some read-only property. it can be use with val not var. benefit of
using lazy is the object will be created only when it is called, otherwise it
will not be created. once the object is initialized, it will use the same
object again when called.//val heavyObject: HeavyClass by lazy {}
-Primary Constructor are declare in the class header.
-secondary constructor declare inside the class using the constructor keyword. we need to explicitly call primary constructor from the secondary constructor.
-The code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated.
// When Object is create than first primary constructor get called after primary constructor init() Block get called than secondary blocked get called.
property of the class can’t be declared inside the secondary constructor. (val or var can not use while declaring)
-we can use the object keyword to make Singleton class
-We also use companion object to achive singlton.// by declaring the companion object, we can access the members of the class by class name only(which is without explicitly creating the instance of the class).
9] Object
Limitation:
in object we dont have Constructor
An object cannot be instantiated like
the way a class is instantiated.
An object gets instantiated when it is
used for the first time.(Lazy with)
10] Scope
function:(let, run, with, also, apply)
scope function are functions that executes a block of code in context of an object. it create a temp scope.
10.1] -let(): it will used for if value is
not null lets execute a block OR return a result of call Chain
i.e nullableString?.let {if nullable
string is not null then executes this
block}
10.2] -apply () : its also used for initialize object but its going to return a same object
10.3] -also() : its used for debugging purpose and get the result in the mid of chain .
10.4] -with() :use case for with is
introducing a helper object whose properties or functions will be used for
calculating a value.
val numbers =
mutableListOf("one", "two", "three")
val firstAndLast =
with(numbers) {
"The
first element is ${first()}," +
" the
last element is ${last()}"
}
println(firstAndLast)
10.5] -run() : When we want to initialize a object
and perform some operation on it but its going to return different object.
i.e fun main(){
val info =Person("Dev"
"25").run{
this.address ="pune"
this.getInfo()
} // run ends
}
11]
Extension function:
It is member function of class which
is define outside the class. eg. fun
<class_name>.<method_name>()
fun String.clearString(string:
String){
println("String:: "+string.substring(1,string.length-1))
}
12] Lambda
Function
Lambda is a function which has no
name. Lambda is defined with a curly braces {} which takes variable as a
parameter (if any) and body of function.
The body of function is written
after variable (if any) followed by -> operator.
13]
**higher-Order Functions:
A higher-order function is a function
which have functions as parameters or we can returns a function. eg fun
passMeFunction(abc: () -> Unit) {}
fun operation(): (Int) -> Int {
return ::square }
fun square(x: Int) = x * x
14] Data
Class:
Data classes are model classes which
we create to hold data. In java we create pojo class with getter and setter
function which lot of boiler plate code.
In kotlin we just have to write data
class classname and it's member variable.
It compile automatically generate
utility methods for class. It generate getter, setter, component & copy
method. Data class create equal, hashcode and tostring method.
-Inline function is instruct compiler to insert complete body of the function, wherever that function used in the code.
this increase the bytecode size slightly but saves us lot of memory.
-Noinline can be used when we have an inline function with multiple lambdas as parameters and we don't want to inline all of them.
-Crossinline helps us enforce the control flow (return statement) of lambda functions passed
16]
**Access Modifer in Kotlin:(private, protected, public and internal)
public: visiblity is everywhere
private: visiblity is inside the same
class only
protected: visiblity is inside the
same class and its subclasses
internal: visiblity is inside the
same module. A module means a group of files that are compiled together. eg. an
IntelliJ IDEA module; a Maven project;
17] two way
of getting data from corouting ?
One shot requests are requests that
are run each time they are called — they always complete after the result is
ready.
Streaming requests are requests that
continue to observe changes and report them to caller — they don’t complete
when the first result is ready."
18]
Suspend functions / suspending
Suspend functions are only allowed to
be called from a coroutine or another suspend function. kotlin corouting api
provide lot of suspending functions to make work easy.
withContext/withTimeout/WithTimeoutOrNull/join/dealy/await/async
19]
**Coroutines
Coroutines is most latest and most
effective way of asynchronous programming and multithreading in android
development. coroutines are like lightweight threads. They are used for co-operative
multitasking where a process voluntarily give away control periodically or when
idle in order to enable multiple applications to be run simultaneously. we can
execute many coroutines in single thread.
When Coroutines are launched within the global scope, they run as long as the application run. suppose coroutines finish it’s a job, it will be destroyed and will not keep alive until the application dies, but suppose coroutines has some work left to do, and suddenly we end the application, then the coroutines will also die, as the maximum lifetime of the coroutine is to the life of the application. Coroutines launched in the global scope will be launched in a separate thread.
The lifecycle scope is the same as the global scope, only difference is that when we use the lifecycle scope,
all the coroutines launched within the activity also dies when the activity dies. If activity dies coroutines will not keep running
A ViewModelScope is defined for each ViewModel in our app. Any coroutine launched in viewmodel scope is automatically canceled if the
ViewModel is cleared. Coroutines are useful here for when you have work that needs to be done only if the ViewModel is active
21]
superwiser scope:
The coroutineScope will get cancel whenever any of its children fail. If we
want to continue with the other tasks, even one task get fails, we use
supervisorScope. A supervisorScope won’t cancel other children when one of them
fails. This scope we use for exception handling the Kotlin Coroutines.
22]
Dispatchers:
There are
majorly three types of Dispatchers IO, Default, and Main.
IO dispatcher is used to do the
network and database-related work. It is basically run on background thread.
Default is used to do the CPU
intensive work.
Main is the UI thread of Android.
23] withContext
withContext is nothing but another way
of writing the async where one does not have to write await(). When
withContext, is used, it runs the tasks in series instead of parallel.
24] Launch
vs Async:
launch{} does not return anything and
the async{} returns an instance of Deferred<T>, which has an
await()function that returns the result. //Deferred is a Job that has a result.
launch: fire and forget
async: perform a task and return a
result
We use RunBlokcing mostly for testing. runBlocking is a coroutine function which not providing any context,
it will run on the main thread. It's Runs a new coroutine and blocks the current thread interruptible until its completion.
We can not use this function from a coroutine. //It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
26] Infix
function:
It is function which we call without
dot and breket or paranthysis. Using infix function provides more readability
to a function
eg. and, or , shr
// user defined infix member function
infix fun square(n : Int): Int{
val num = n * n
return num
}
}
val m = math()
val result = m square 3 // call this infix fuction
27]
Collection in kotlin:
In Kotlin
basically we have mutable and Immutable collection.
Immutable Mutable
List MutableList
Map MutableMap
Set MutableSet
28] Open
keyword:
In Kotlin, classes, functions and the
variables are by default final in nature
i.e. they can’t be inherited from any other class.
So, to make it inheritable from
other classes, we use the open keyword with the class, function, and variable
name.
to make a class inheritable to the
other classes, we mark it with the open keyword otherwise we will get an error
like “type is final so can’t be
inherited”.
29]
safecall(?.) and nullcheck(!!)
The difference between the Safe call
and Null check is that we use Null checks (!!) only when we are confident that
the property
can’t have a null value. And if
we are not sure that the value of the property is null or not then we use Safe
calls(?.).
30] What
is difference between safecall operator and by using let() in kotlin ?
once you put code in let{} block then
no need to write every time safe call operator (?) .
31] Elvis
Operator(?:)
first operand ?: second operand
right-hand side expression is
evaluated only if the left-hand side is null.
a ?: b is just shorthand for if (a !=
null) a else b
32]
Ternary Operator:
ternary operator expression a ? b : c
when(a) {
true -> b
false -> c
}
33] :: is
used for Reflection in kotlin
Class Reference val myClass =
MyClass::class
Function Reference this::isEmpty
Property Reference
::someVal.isInitialized
Constructor Reference ::MyClass
34]
Primitive kotlin
Kotlin doesn't have primitive type (I
mean we cannot declare primitive directly). It uses classes like Int , Float as
an object wrapper for primitives. When kotlin code is converted to jvm code,
whenever possible, "primitive object" is converted to java primitive
35] Enums
Kotlin enums are classes like Java
enums. Each of the enum constants acts as separate instances of the class and
separated by commas. Enums increases readability of our code by assigning
pre-defined names to constants. enum constants are instances of an Enum class,
the constants can be initialized by passing specific values to the primary
constructor.
36]
**Sealed class:
Sealed class gives us to flexiblity
to having differnt classes of subclasses. Seald classes are abstract by default
but the advantages of use sealed class over abstract class is that, it offers
restricted numbers of hierarchy.
Suppose we handling the different
senario of response we can identify the different cases using when(). major advantages
is no else case required because we know all the subclasses of Sealed class
handle that much.
Sealed class is build on top of Enums
.
Actully in Enums can hold one value
like .. Success or Failure
But in Sealed classes we can have
values for those keys or more describtion for it like handling exception. i.e
sealed class Result<out T : Any>
{
data class Success<out T :
Any>(val data: T) : Result<T>()
data class Error(val exception:
Exception) : Result<Nothing>()
}
- Sealed class rules
- Sealed classes are abstract and can have
abstract members.
- Sealed classes cannot be instantiated
directly.
- Sealed classes cannot have public
constructors (The constructors are private by default).
- Sealed classes can have subclasses, but
they must either be in the same file or nested inside of the sealed class
declaration.
- Sealed classes subclass can have subclasses outside of the sealed class file.
37] What
is KTX?
Android KTX is a set of Kotlin
extensions that are included with Android Jetpack and other Android libraries.
KTX extensions provide concise,
idiomatic Kotlin to Jetpack, Android
platform, and other APIs. To do so, these extensions have many Kotlin language
features, like
Extension functions
Extension properties
Lambdas
Named parameters
Parameter default values
Coroutines
38] What
is labels in kotlin?
Any expression written in Kotlin is called labels . For example, if we are having a for-loop in our Kotlin code then we can name that for-loop expression as a label and will use the label name for the for-loop . So, basically we are giving one name to the for-loop and by doing so whenever we want to call the same for-loop , we can just call it by the label name.
loop@ for (i in 1..10) {
// some code goes here
}
39] What are content providers: Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps
40] Intent v/s PendingIntent v/s
Sticky Intent
Intent: Intent
is a message passing mechanism between components of android, except for
Content Provider. You can use intent to start any component.
PendingIntent:
A PendingIntent is a token that you give to a foreign
application (e.g. NotificationManager, AlarmManager, Home Screen
AppWidgetManager or other 3rd party applications), which allows the foreign
application to use your application’s permissions to execute a predefined piece
of code.
If you want a foreign application to perform any Intent operation at future
point of time, then we will use PendingIntent.
Sticky Intent:
Sticks with android, for future broadcast listeners. For example
if BATTERY_LOW event occurs then that intent will be stick with android so that
if any future user requested for BATTER_LOW, it will be fired.
An intent that is used with sticky broadcast, is called as
sticky intent. This intent will stick with android system for future broadcast
receiver requests.
sendStickyBroadcast()
performs a sendBroadcast(Intent)
known as sticky,
i.e. the Intent you are sending stays around after the broadcast is complete,
so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver,
IntentFilter)
. In all other ways, this behaves the same as sendBroadcast(Intent)
. One example of a
sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED
. When you call registerReceiver()
for that action —
even with a null BroadcastReceiver — you get the Intent that was last broadcast
for that action. Hence, you can use this to find the state of the battery
without necessarily registering for all future state changes in the battery.
41]
Types of Services
These are the three different types of services:
1] Foreground: A foreground service performs some operation that is noticeable
to the user. For example, an audio app would use a foreground service to play
an audio track. Foreground services must display a Notification. Foreground services continue running even when the user
isn't interacting with the app.
When you use a foreground service, you must display a notification so
that users are actively aware that the service is running. This notification
cannot be dismissed unless the service is either stopped or removed from the
foreground.
2] Background: A background service performs an operation that
isn't directly noticed by the user. For example, if an app used a service to
compact its storage, that would usually be a background service.
3] Bound: A service is bound when
an application component binds to it by calling bindService(). A bound service
offers a client-server interface that allows components to interact with the
service, send requests, receive results, and even do so across processes with
interprocess communication (IPC). A bound service runs only as long as another
application component is bound to it. Multiple components can bind to the
service at once, but when all of them unbind, the service is destroyed.
42] What is an intentService?
IntentService
is an extension of the Service component class that handles asynchronous requests
(expressed as Intents) on demand. Clients send requests through Context.startService(Intent) calls; the service is started as
needed, handles each Intent in turn using a worker thread, and stops itself
when it runs out of work.
This
"work queue processor" pattern is commonly used to offload tasks from
an application's main thread. The IntentService class exists to simplify this
pattern and take care of the mechanics. To use it, extend IntentService and
implement onHandleIntent(android.content.Intent). IntentService will receive the
Intents, launch a worker thread, and stop the service as appropriate.
All
requests are handled on a single worker thread -- they may take as long as
necessary (and will not block the application's main loop), but only one
request will be processed at a time.
43] What
are ViewModel and How do they work on Android? : A class is designed to store
and manage UI-related data in a lifecycle conscious way. The ViewModel
class
allows data to survive configuration changes such as screen rotations.
44]
What is LiveData?: It is an observable
data holder class. Unlike a regular observable, LiveData is lifecycle-aware,
meaning it respects the lifecycle of other app components, such as activities,
fragments, or services.
45] What is Dependency Injection and Why
to do that? : Reduced Dependencies: Classes often require
references to other classes. For example, a Car
class
might need a reference to an Engine
class. These required classes are
called dependencies,
and in this example the Car
class is dependent on having an
instance of the Engine
class
to run. Advantages:
Reduced Dependency Carrying, More Reusable Code, More Testable Code, More
Readable Code
46]
map vs flatMap
- FlatMap is used to combine all the items of lists into one
list.
- Map is used to transform a list based on certain conditions.
Map |
FlatMap |
The function passed to map() operation returns a
single value for a single input. |
The function you pass to flatmap() operation returns
an arbitrary number of values as the output. |
One-to-one mapping
occurs in map() |
One-to-many mapping
occurs in flatMap() |
Only perform the mapping |
Perform mapping as well as flattening. |
Produce a stream of value |
Produce a stream of stream value |
map() is used only for transformation. |
flatMap() is used both for transformation and mapping. |
47] Differene between Service and
IntentService
Service |
IntentService |
If the task doesn’t require any and also not a very
long task you can use service. |
If the Background task is to be performed for a long
time we can use the intent service. |
we use the method onStartService() to start the service |
we use the method Context.startService(Intent) to start the intent service |
Service will always run on the main thread. |
intent service always runs on the worker thread triggered
from the main thread. |
There is a chance of blocking the main thread. |
tasks will be performed on a queue basis i.e, first
come first serve basis. |
To stop service we have to use stopService() or stopSelf() |
No need to stop the service, it will stop automatically. |
Easy to interact with the UI of the application. |
Difficult to interact with the UI of the
application. |
48] What is KAPT?
KAPT
stand for kotlin annotation processing tool.
49] What is an inline function?
An Inline function is a kind of function that is declared
with the keyword "inline" just before the function declaration.
Once a function is declared inline, the compiler does not allocate any memory
for this function, instead the compiler copies the piece of code virtually at
the calling place at runtime
50] Difference between Coroutine and thread
Coroutine |
Thread |
A coroutine is a program, one of the cooperative types of subprograms
which allows to pause and resume at the time of execution. |
Threads, on the other hand, are built-in processes. |
Coroutines are a form of sequential processing, and one is executed at
a time. |
Threads are conceptually a form of concurrent processing, i.e.,
multiple threads get executed at any given time. |
Coroutines are not bound to any particular thread. |
Whereas, for threads, the Operating system switches threads
preemptively based on the scheduler. |
Coroutines start execution in one thread, suspend the execution and
resume on other thread. |
Whereas a thread can be kept blocked for a certain period of time and
cannot be used until its work gets completed. |
As coroutine is user-friendly and light weight, scheduling is
controlled by the user completely. |
Thread is a process entity and basic unit of CPU and scheduler
dispatch; it can run independently. |
Coroutine has its own register context and stack. |
Thread does not have its own system resources but has few resources
that are essential such as a set of registers and stack. |
When a coroutine scheduler switches, register context and stack are
saved to another place. |
Threads can share all the resources owned by the process and threads
belonging to the same process. |
In coroutines, the operating stack basically does not have kernel
switching overhead and access global variable without a lock. Hence context
switching is faster. |
In threads, communication is through shared memory. Hence context
switching is faster, resource overhead is less, but the process is not stable
enough and losses data easily. |
Coroutines are Asynchronous. |
Threads are of Synchronous mechanism. |
Coroutines have user-mode memory space given by threads for data
storage. |
Threads have Kernel memory space for data storage. |
Application code in Coroutines uses code for on-site storage and
restoration. |
Switch operation is completed in the Kernel layer itself, and the
application layer will call syscall, underlying functions given by the kernel
layer. |
In Coroutines, task scheduling is carried out by a specific scheduler
for user-mode realization. |
In Threads, task scheduling is realized by Kernel, preemptive mode
depending on various locks. |
Coroutines have a voice support level for few programming languages
such as Go, Python, Lua, etc. |
Threads have a voice support level for most of the programming
languages. |
In coroutines, there is no uniform specification, and implemented by developers
at the application layer and is customizable. |
For threads, implementation specifications change according to modern
operating system specifications. |
Coroutines use a function call and resumed later. |
Threads use interrupt-based events to change context compared to what
coroutines use. |
51] What is WorkManager
Android WorkManager is a background processing
library which is used to execute background tasks which should run in a
guaranteed way but not necessarily immediately. With WorkManager we can enqueue
our background processing even when the app is not running and the device is
rebooted for some reason. WorkManager also lets us define constraints necessary
to run the task e.g. network availability before starting the background task.
Android WorkManager is a part of Android Jetpack (a suite of
libraries to guide developers to write quality apps) and is one of the Android
Architecture Components (collection of components that help developers design
robust, testable, and easily maintainable apps).
52]
Launch Mode in Android
1. Standard
This is the default launch mode of activity (If not
specified). It launches a new instance of an activity in the task from which it
was launched. Numerous instances of the activity can be generated, and multiple
instances of the activity can be assigned to the same or separate tasks. In
other words, you can create the same activity multiple times in the same task
as well as in different tasks.
2. Single Top
If
an instance of the activity already exists at the top of the current task in
this launch mode, no new instance will be generated, and the Android system
will send the intent data through onNewIntent (). If an instance does not exist
on top of the task, a new instance will be generated. You can use this launch mode
to generate numerous instances of the same activity within the same task or
across tasks, but only if the identical instance does not already exist at the
top of the stack.
3. Single Task
In this method of operation, a new task is always generated, and a new instance is added to the task as the root one. If the activity already exists on another task, no new instance is created, and the Android system transmits the intent information via the onNewIntent() function. At any one time, there will be just one instance of the activity.
4. Single Instance
This is a highly unique start option that is only used in programs with a single activity. It works similarly to Single Task, except that no additional activities are generated in the same task. Any further activity initiated from this point will result in the creation of a new task.
Comments
Post a Comment