Android 253 QSN and Answer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Android Interview Questions:

1. Draw architecture diagram of android framework.

2. Which kernel(Operating system) is used in android?


Ans : Linux Kernel
3. In which language android framework is written?
Ans: Java
4. What does DVM stand for ?
Ans: Dalvik virtual Machine
5. Why DVM why not JVM?
Ans: Conceptually, there is little difference from an application level between a DVM and a
JVM. Architecturally, there is a major difference between the registerbased DVM and the
stack-based JVM.
Both use a VM code model. However, the DVM uses registerbased opcodes that are
comparable to the register-based bytecode instructions that most of the target platforms
already execute. This includes architectures such as those available from ARM and MIPS
and the x86-compatible architectures from Intel, AMD, and VIA Technologies.
Google developed Android and chose DVM for several reasons. First, there were licensing

issues with most JVMs. Next, the DVM should be more efficient in terms of memory usage
and performance on a register-based machine. DVM is also supposed to be more efficient
when running multiple instances of the DVM. Applications are given their own instance.
Hence, multiple active applications require multiple DVM instances. Like most Java
implementations, the DVM has an automatic garbage collector.

6. Which layer does DVM sits?


Ans: library layer
7. What is the latest version of android? Can you tell me what is the new concepts
ans: lollypop UI design,batery backup,notification,performance
added in this version?
8. Explain life cycle of activity?

9. If I have a broadcast receiver that updates my UI frequently, then where should I


register that broadcast receiver in my activity life cycle functions?
Ans : onStart() function will be called just before your activity will be made visible to the user. So
any thing that affects UI has to be registered in onStart() function.
10. Can I save all my databse tables updations in onStop() of activity? If not explain
why and also explain where should I save db tables?
Ans: No, because onStop() may not be called in some situations.
Description : In case of low memory or configuration changes, there is a chance that android may

force-kill your application before reaching onStop(). onPause() is the only function that will be
called with out fail before killing the application. so save all persistent data like DB tables in
onPause() only. Note : We can't save all database tables in onSaveInstanceState, because that
function will not be called if user presses back button.
11. What is difference between persistent data and transient data, give one example.
Also tell me which activity life cycle function I need to use to save them?
Ans:(C) Persistent data is permanent data that we store, eg in database tables, and transient data is
logical data that we use in programming logic. Description : Persistent data means permanent, and
transient means temporary.
If it is not necessary to save the data permanently and you only want to save the state of the UI, you
can use the onSaveInstanceState event to store the state in a Bundle. This should not be relied upon
to save data since the event is not part of the activity lifecycle and is only triggered by the UI when
the activity needs to be recreated or is sent to the background, but not when it is destroyed
permanently : it is meant for storing transient view states. Some of the data is already saved by the
Android SDK, but you may need to save extra information, for example if you have custom
controls. When the user navigates back to the activity and the state of the UI needs to be restored,
the bundle containing the state information is accessible from the onRestoreInstanceState event
raised if the activity was still in memory, or from the onCreate event raised if the activity was
recycled and needs to be recreated.
12. What will happen if I remove super.oncreate() from oncreate() function of
activity?
Every Activity you make is started through a sequence of method calls. onCreate() is the first of
these calls.
Each and every one of your Activities extends android.app.Activity either directly or by subclassing
another subclass of Activity.
In Java, when you inherit from a class, you can override its methods to run your own code in them.
A very common example of this is the overriding of the toString() method when
extending java.lang.Object.
When we override a method, we have the option of completely replacing the method in our class, or
of extending the existing parent class' method. By calling super.onCreate(savedInstanceState);, you
tell the Dalvik VM to run your code in addition to the existing code in the onCreate() of the parent
class. If you leave out this line, then only your code is run. The existing code is ignored completely.
However, you must include this super call in your method, because if you don't then
the onCreate() code in Activity is never run, and your app will run into all sorts of problem like
having no Context assigned to the Activity (though you'll hit a SuperNotCalledException before
you have a chance to figure out that you have no context).
In short, Android's own classes can be incredibly complex. The code in the framework classes
handles stuff like UI drawing, house cleaning and maintaining the Activity and application
lifecycles.super calls allow developers to run this complex code behind the scenes, while still
providing a good level of abstraction for our own apps.
13. What is the purpose f super.oncreate() ?
Ans : Go to qsn 12
14. Show me how does intentfilter of main activity looks like? What is the action and
what is the category?
<activity

android:name="com.example.project.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

Description : action.MAIN - says this activity is the main activity (starting point) for this
application. category.LAUNCHER - says this activity should appear in the home screen's launcher.

action : Declares the intent action accepted, in the name attribute. The value must be the
literal string value of an action, not the class constant.

category: Declares the intent category accepted, in the name attribute. The value must be
the literal string value of an action, not the class constant.
android:name The name of the action. Some standard actions are defined in the Intent class
as ACTION_string constants. To assign one of these actions to this attribute,
prepend "android.intent.action." to the string that follows ACTION_.
15. What is the importance of version code and version name attributes in manifest
file?
it tells your applications version number and name. It will be used when you want to update your
app in google play store Description : Version no and name will be useful when you upload some
application to play store and wanted to update it. When you are upgrading your application then you
can increment the version number so that users of your application will get notification on their
phones about the latest updates available.
16. Can one application have more than on manifest file?
17. Can I create activity without xml file?
Yes, with the exception of the manifest and perhaps some theme declarations (I'm not sure if there
are public Java equivalents for everything we can set up via themes).
Is it a good idea? Heavens, no.
The point behind the resource system is to allow Android to transparently hand you the proper
resources needed by the device at the present moment, based on both permanent device
characteristics (e.g., screen density) and transient device characteristics (e.g., portrait vs. landscape
orientation).
To avoid the resources, you will have to go through a bunch of if statements to determine which
hunk of Java code to run, detecting all these things by hand. This gets significantly more
complicated once you take into account changes in Android itself, as new configuration changes
and values get added, making it difficult for you to support everything you need to in a backwardscompatible way.
Along the way, you will lose all tool support (drag-and-drop GUI building, MOTODEV Studio's
string resource assistants, etc.), outside of plain Java editing and debugging.
You seem to be placing your own personal technical inclinations ahead of all other considerations.
If this is some small personal project, that may be a fine attitude. If you are creating code to be
developed and/or maintained by others over time, though, you need to factor in the needs of those
other developers, and they may be much more open to XML than are you.
18. How to create ui without using xml file, show with one example on how to create
activity with a linear layout and with two buttons and without having xml file?
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// creating LinearLayout
LinearLayout linLayout = new LinearLayout(this);
// specifying vertical orientation
linLayout.setOrientation(LinearLayout.VERTICAL);
// creating LayoutParams
LayoutParams linLayoutParam = new
LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// set LinearLayout as a root element of the screen
setContentView(linLayout, linLayoutParam);
LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(this);
tv.setText("TextView");
tv.setLayoutParams(lpView);
linLayout.addView(tv);
Button btn = new Button(this);
btn.setText("Button");
linLayout.addView(btn, lpView);
LinearLayout.LayoutParams leftMarginParams = new
LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
leftMarginParams.leftMargin = 50;
Button btn1 = new Button(this);
btn1.setText("Button1");
linLayout.addView(btn1, leftMarginParams);
LinearLayout.LayoutParams rightGravityParams = new
LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rightGravityParams.gravity = Gravity.RIGHT;
Button btn2 = new Button(this);
btn2.setText("Button2");
linLayout.addView(btn2, rightGravityParams);
}

19. Give me two examples of configuration changes in phone?


flipping the phone
keyboard on language
settings change
Description : configuration changes include: rotating the phone, having virtual keypad on, and
changing language settings in settings.
20. What is the mandatory life cycle function that will get called in case of
configuration changes?
In case of low memory or configuration changes, android will call both onPause() and
onSaveInstanceState() with out fail. Exception: there is one exceptional case, that is if
programmer is handling configuration changes, then in that case it will not call those functions.

21. Can I save large images downloaded from internet in onsaveinstancestate() ?


onSaveInstanceState() function has to be used for saving small objects (transient states). If we want

to save large objects use onRetainNonConfigurationInstance() function. Or else we can make that
image as static, so that the image will be loaded only once. More documentation :
onSaveInstanceState() function has to be used for saving small objects, not for heavy objects. If you
want to save heavy images on phone rotation, then use any of below techniques: 1. If you want to
save large objects use onRetainNonConfigurationInstance() function. 2. Or else we can make that
image as static, so that the image will be loaded only once. Meaning: On downloading an image
from network, make it pointed by a static variable. If user rotates the phone, since android kills that
activity and recreates it, just put a if condition check if that static variable is not null, then only
download again. As you know static variables will be created only once, it will not download again.
22. What is the difference between this & getapplicationcontext() ? which one to use
when?
his points to current context, application context points to entire process. if your context is of entire
life time of process then use app context, else this.
Description : this pointer always points to current class object, app context will point to entire
process. there is only one app context. if you want to use some control whose life time is through
out your application life time then go for app context, else use this pointer (activity context).
getApplicationContext() - Returns the context for all activities running in application.
getBaseContext() - If you want to access Context from another context within application you can
access.
getContext() - Returns the context view only current running activity.
23. Every application will have by default one thread? True or false?
Default android will allocate one main thread called as (UI thread) to every process or application.
24. What is ANR (application not responding)? What is the reason for this problem
and what is the solution for that problem?
ANR - will occur if we are doing any other heavy functionality along with UI in single Main
Thread.If two heavy functionalities happen in single thread, it will delay response to user actions,
which may irritate user, and hence stop your process. Solution - Run only UI components in Main
Thread.
25. Main thread will have a looper , true or false?
only handler threads will have loopers
. Description : Main Thread is a handler thread, so it will have looper enabled. Normal threads
looper will be in disabled mode, where as handler threads will have their loopers enabled. but if we
want we can prepare loopers for normal threads also.
26. By default a given process will have how many threads? Who will create those
threads?
1 main thread created by android system
Description : Since every process requires a thread to run with CPU, by default android system will
create one main thread for every application
27. What will happen if I remove oncreate() & onstart() from activity? Will it run?
nothing will happen it will run perfectly
Description : It is a standard, that programmer has to implement corresponding life cycles methods
of activity based on the functionality supported. But one can skip those functions if programmer
wish to.

28. Can I have an activity without UI?


yes, if it is doing some functionality with out UI Description : Generally every activity will have UI
(User Interface) screens. But if programmer wants he can omit UI and do some background
functionality with an Activity. Note: To do background functionality its better to use service than an
activity with out UI. It makes more sense.
29. What is the difference between intent, sticky intent, pending intent?
intent - is a message passing mechanism between components of android except for Content
Provider;
Sticky Intent - Sticks with android, for future broad cast listeners;
Pending Intent - Will be used when some one wants to fire an intent in future and may be at that
time that app is not alive.
Description : intent - is a message passing mechanism between components of android, except for
Content Provider. You can use intent to start any component. Sticky Intent - Sticks with android, for
future broad cast 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;
Pending Intent - If you want some one to perform any Intent operation at future point of time on
behalf of you, then we will use Pending Intent. Eg: Booking a ticket at late night when your
application is not running. In this scenario we will create a pending intent to start a service which
can book tickets at late night and hand it over to Alarm Manager to fire it at that time.
30. What is the difference between implicit intent and explicit intent, give one
example?
Implicit intent - Intent with out target component name;
Explicit intent - Intent with target component name.
Description : Implicit intent - Intent with out target component name;
Explicit intent - Intent with target component name.
EG: if we want to start a new screen or activity with in our application, then we clearly know what
is that activity name because both activities are in same application. In such cases we will use
explicit intent. Assume that we want to launch Gallery activity from our application, then we don't
know exact name of that gallery activity because gallery is a different application, in that case we
will use implicit intent with some matching actions.
Eg for Explicit intent:
Intent in = new Intent(getApplicationContext(), SecondScreen.class); //target component name
startActivity(in);
Note: Explicit intents are specifically used to start other components of same application.
Eg for Implicit intent:
Intent in = new Intent(); //no target component name
in.setAction(Intent.ACTION_GET_CONTENT);
in.setType("image/*");
startActivity(in);
Note: Iplicit intents are specifically used to start components of other applications.
31. How many components are there in an intent?
Intent can have a.action, b.data and its type, c.category, d. extras, e.Target Component name, f.
some extra flags.

32. Can I give more than one action in a given intent?


Intent can have maximum one action, but it is not mandatory. some times it can have 0 actions also
(in case of explicit intent). So an intent can have 0-1 actions.
33. Can I give more than one category in a given intent?
Yes. You can have 0 or n number of categories in intent Description : Unlike actions, an intent can
choose to have 0 or n number of categories.
34. Create an intent to start calling a number 12345 ?
Intent in = new Intent();
in.setAction(Intent.ACTION_CALL);
in.setData(Uri.parse("tel:12345"));
startActivity(in);
35. what is the importance of putextras in intent? How is it different from setdata() ?
any way both are passing data only , so in that case what is the difference?
setData() - is to pass data on which to take action.
putExtra() - is to send extra information about this intent.
Description : setData() - is to pass data on which to take action.
putExtra() - is to send extra information about this intent.
EG: if one is starting an activity to perform ACTION_CALL, then he has to set number in
setData(). this function will contain on which data target component has to take action. if one want
to pass extra details also, then only use putExtra().
36. What is the difference between thread and service?

Service is like an Activity but has no interface. Probably if you want to fetch
the weather for example you won't create a blank activity for it, for this you
will use a Service.
A Thread is a Thread, probably you already know it from other part. You need
to know that you cannot update UI from a Thread. You need to use a Handler
for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as
it can help with it's methods, and there are two methods that run on UI thread,
which is good to update UI components.

37. Can I have a service without thread?


yes, you can have service running in main thread only if you are not running any activity in Main
thread.
Description : Service is a component that performs some operation in the background with out
having UI. But it doesn't mean that it will have separate thread to do it. By default if programmer
doesn't provide any thread for the service, then it runs in Main UI thread. Since it is not good
practice to run Activity & Services in single thread, it is suggestible to have separate thread for the
service, except in few cases like where a given application is not having any activity in it.
38. If I want to touch ui from another thread can I touch directly? What will happen if
I do so?

39. How to achieve inter thread communication?


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running
in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.It is implemented by following methods of Object class:
wait() Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
Notify() Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened.
NotifyAll() Wakes up all threads that are waiting on this object's monitor.

40. What is the difference between thread and handler thread?


Threads are generic processing tasks that can do most things, but one thing they
cannot do is update the UI.
Handlers on the other hand are background threads that allow you to
communicate with the UI thread (update the UI).
So for example show a toast or a update a progress bar via a message (Runnable)
posted to a handler but you can't if you start this runnable as a thread.
With handler you can also have things like MessageQueuing, scheduling and
repeating.
I am yet to encounter a situation where I needed a thread in android.
I mostly use a combination of AsyncTasks and Handlers.
Handlers for the aforementioned tasks.
AsyncTasks for download/ data fetching and polling etc.
You can read the developer article here "Painless Threading" for more threading in
android.
Correction: Each Handler instance is associated with a single thread and that
thread's message queue. They are not threads in their own behalf.

41. what will happen if I bind a service from a broad cast receiver, is there any
problem?
No, One should not bind a service from Broadcast receiver. because, broadcast receivers will have a
time limit of 10 seconds. establishing connection to a service may take more time.
Description:One should not bind a service from Broadcast receiver. The reason is broadcast
receivers are light weight components, where it has to finish its functionality with in not more than
10 seconds maximum. Else android may forcefully kill your receiver. Binding (establishing
connection to) a service may take more than 10 seconds in some worst cases, that's why android
won't allow it. Rules for Broadcast Receivers:
1.Broadcast receivers will not have any UI(mostly) and it will have only background logic.
2.Broadcast receivers will have the maximum time limit of 10 sec to finish its functionality
otherwise it will crash.
3.You should not do long running operations or asynchronous operations in the receiver.
Example: a. Preparing SD card.
b. Uploading / Downloading files from internet.
c. Creating Db files.
d. Binding to services
4.Do not show dialog to the user in broadcast receiver. (this is asynchronous operation)
5.You can use toast or Notifications.
6.Dont write any heavy functionalities.
42. Can I start a service from a broadcast receiver?
Yes https://blog.nraboy.com/2014/10/use-broadcast-receiver-background-services-android/
43. How to start a service with foreground priority?
startForeground (int id, Notification notification), use this function in onCreate() of your service.
Description : Generally services will run in background, which is of 3rd priority. if you feel that
the service is critical for user, then you can increase its priority by making it foreground service.
Use function startForeground (int id, Notification notification), in onCreate() of your service to
make this service as foreground service. Foreground services will be treated with highest priority, so
android will ensure it will not kill these services even in case of low memory situations. Eg: MP3
player service is a foreground service.
44. What is the difference between broadcast receiver and a service, where most of
the cases both will not have any UI, in that case which one I should use?
BroadcastReceiver - is like gateway for other components, can do small back ground functionality
with in 10 seconds. Services - can do long running operation in the background with out having UI,
and no time limit for it.but both receiver and service both can interact with UI if they want to.
Broadcast Receivers have time limit of 10 seconds, and they respond to broadcasted messages.
Description : BroadcastReceiver - is like gateway for other components, can do small back ground
functionality with in 10 seconds. Services - can do long running operation in the background with
out having UI, and no time limit for it.but both receiver and service both can interact with UI if they
want to. services will not have time limit of 10 seconds, receivers respond to broadcasted

45. If I start an activity with implicit intent, and there is no matching intentfilter then
what will happen?
it will throw run time exception - activityNotFoundException, and crashes if it is not handled
properly.
Description : for startActivity(intent), if there are no matching target components or activities, then
it will throw run time exception - ActivityNotFoundException, and will crash the program if this
exception is not handled.
46. If I send a broad cast with implicit intent, and there is no matching intentfilter
then what will happen?
Nothing will happen, but it will not launch any receiver.
Description : Unlike startActivity() and startService(); sendBroadcast() will not throw any run time
exception. If there are no target components available for this broadcast it will keep quiet. It is
because in case of activity and service, action is yet to be performed but in case of
broadcastReceiver action is already over and we are just informing it to every one.
47. Write a broadcast receiver that gets triggered once phone boot is done?
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></usespermission>
<receiver android:name="BroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
48. What will happen if I dont pass any action in an implicit intent, will it trigger any
component?
49. Can I start a content provider using an intent?
not possible. Using intent you can't trigger a content provider.
because, we use content resolver to communicate with content provider
Description : Intents will be used to communicate or start components of android. Only exception
is content provider. You can start an activity, service, and a broadcast receiver using intent but not
content provider. For content provider we have to use content resolver to communicate.
50. I have one intent filter without any action, then can I trigger this component from
outside of this application?
No, with out any action no one can trigger or start that component from outside world. Description :
Without any action in the intent filter, it is not possible to start that component from outside world.
intent filters, action will be considered only for implicit intents. Note: You can explicit intents only
with in the application.
51. Can I have more than one action in my intentfilter?
intent filters can have 0 or more number of actions. But if that component has only one intent-filter
with 0 actions, then that component can be triggered using only explicit intents.
a given intent-filter can have more than one action because, a given component can do more than
one action. EG: notepad can perform two actions ACTION_VIEW & ACTION_EDIT on an
existing note pad file.

52. Can I have more than one category in my intentfilter?

53. Can I have extras in my intentfilter?


intent-filter tag will not have extra tag. it has only action, category, and data tags. extra tag will not
be used while performing tests for intent resolution.
54. I want to start something in the background in my activity, should I use thread or
should I start service? Why?
If that background functionality is co-related with activity, then use thread. else launch it in a new
service with thread in the service.
Description : It always depends on the requirement. if the background functionality is related or
tightly coupled with activity, then use thread. but if you want some thing to do in background
irrespective of whether activity is alive or not, then go for service-with thread.
55. If I crate a thread in my activity and if I stop my activity what will happen to that
thread, will it be alive or dead?
it will be alive, but its priority will be least compared to thread in a service.
Description : once a thread is created, it will run independently of who has created until the work
given to that thread is finished. but in case of low memory scenarios a thread created by activity and
which is running in the background will have more susceptibility of being killed by android system.
More worse is android can not recreate the thread which was killed because of low memory. but if
that thread was in service, then chances of getting killed by android due to low memory may be less
than previous situation. even if android system kills the thread, again it will start the service when
memory resources are available and service can re-initiate that killed thread.
56. If I start a service from my activity and if I stop my activity what will happen to
that service, will it be alive or dead?
service will be keep running in the background, but it can stop itself when the work given to it is
done. Or others also can kill that service using stopService(), or android also can kill the service
forcefully in case of low memory scenarios.
Description : service will be keep running in the background, even if the activity which has created
is no more alive.But it can stop itself when the work given to it is done. Or others also can kill that
service using stopService(), or android also can kill the service forcefully in case of low memory
scenarios.
57. How many ways are there to kill a service?
58. If I want my service to allow binding, then what is the function that I need to
implement in my service class?
59. Can I create a customized textview?
60. How many ways you can store persistent data?
61. What is the use of content provider? Will it support shared preferences?
62. If I want to share some data with outside applications then what is the component
in android to use?
63. Can one application access other app database directly?
64. Where does the database get stored?
65. What is the extension of your shared preference file? Where is it stored?

import
import
import
import
import

android.content.Context;
android.graphics.Canvas;
android.graphics.Typeface;
android.util.AttributeSet;
android.widget.TextView;

public class FontTextView extends TextView {


public FontTextView(Context context) {
super(context);
Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf");
this.setTypeface(face);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf");
this.setTypeface(face);
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Typeface face=Typeface.createFromAsset(context.getAssets(), "Helvetica_Neue.ttf");
this.setTypeface(face);
}
protected void onDraw (Canvas canvas) {
super.onDraw(canvas);
}
}
<com.util.FontTextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/accountInfoText"
android:textColor="#727272"
android:textSize="18dp" />

66. What is the default shared preference file name of an activity?


<Activityname>.xml Description : By default if programmer don't give any name to shared
preference, then activity name will be taken as shared preference file with .xml extension.
67. What is the difference between task, process, application, and thread?

Process:
A process is an instance of a computer program that is being executed. It contains
the program code and its current activity. Depending on the operating system
(OS), a process may be made up of multiple threads of execution that execute
instructions concurrently. Process-based multitasking enables you to run the Java
compiler at the same time that you are using a text editor. In employing multiple

processes with a single CPU,context switching between various memory context is


used. Each process has a complete set of its own variables.

Thread:
A thread of execution results from a fork of a computer program into two or more
concurrently running tasks. The implementation of threads and processes differs
from one operating system to another, but in most cases, a thread is contained
inside a process. Multiple threads can exist within the same process and share
resources such as memory, while different processes do not share these resources.
Example of threads in same process is automatic spell check and automatic saving
of a file while writing. Threads are basically processes that run in the same
memory context. Threads may share the same data while execution.

Task:

A task is a set of program instructions that are loaded in memory.

68. Does android support multi tasking? If yes explain how to start a new task when
you are already running one task?
Android supports multitasking at app level also. press home button on current task which
will move it to background and then you can start new task from launcher.
there is one more way to start a new task by using FLAG_NEW_TASK when you are starting
a new activity.

69. Does android support multi threading?


Yes, Android supports Multithreading. The most preferred way of implementing
it(other than Thread Pool and Executor) is AsyncTask
AsyncTasc allows you to implement doInBackground(), where your thread can crank
away at its task. This is similar to the functionality you'd get from Thread.
The real magic happens when you
override onPreExecute() and onPostExecute(), which are both executed on the UI
thread. This should keep you from getting messages about your Activity not being
attached.

70. What is the mechanism used by android for Interprocesscommunication?


IPC means Inter process communication : Where two applications or processes will communicate
with each other by passing some data between them.
Since android is meant for embedded and small devices, we should not use serialization for IPC,
rather we can use BINDERs which internally uses parcels. parcel is a sort of light weight
serialization by using shared memory concept.
There are many differences between Binder IPC and Serialization IPC:
1. Serialization is very heavy to use in embedded devices, communication will be very slow.
2. Binders uses Parcels to make IPC very fast.
3. Binders internally uses Shared memory concept which uses less memory while sharing data
between two processes.
Bottom line : Binders uses less memory, and quite fast as it uses parcels. Serialization is very
heavy , takes time to send and receive data, and also it takes more memory compared to binders.

Note : To pass data between activities, services, and receivers use only Bundles. Don&#39;t go
for either serialization or binders.
71. How binder is different from serialization?
Binder uses shared memory concept to do Inter process communication
Description : Serialization and Binders are both IPC mechanisms how to processes will
communicate. Serialization is very heavy as it has to copy hole data and transmit to other process
through channel. But Binders are light weight where both the processes will share or communicate
the data using a shared memory concept. what ever the data has to be shared it will be kept in a
common shared memory and both process's can access that memory to make communication faster.
72. How serialization differ from parcel?
Parcels are used in Binders. We use parcels for only IPCs, for normal serialization we use
serializables.
Description : Parcel is not a general-purpose serialization mechanism.This class is designed as a
high-performance IPC transport. used heavily in IBinders. for normal serialization concepts, use
Serializables. since serializables are heavy and takes time, we use Parcels for IPC in embedded
devices.
73. If I have one application with activity, service, and contentprovider. Then when I
run this program how many process, threads will be created? Is it possible to run these
components in more than one process?
One process, one Thread, Yes it is possible to run in more than one process.
Description : Before loading an application into RAM, a process will be created with a thread by
default. Even though in Linux, an application will be given only one process to run all its
components, it is quite possible that components of a given application can run in more than one
process provided both processes have same Linux user id.
74. What is looper, message queue, and a Handler? Where do you need these
components?
Looper - part of any Thread to loop through message queue. Message Q - part of any thread, will
store incoming messages to this thread. Handler - communication channel between two threads.
Description : Looper - part of any Thread to loop through message queue.This will be used to
check if any incoming message has arrived to this thread. Only one looper exists for a given thread.
Only for handler threads this looper will be activated, for other normal threads this will be in
passive or inactive mode. Message Q - part of any thread, will store incoming messages to this
thread. For any thread only one message Q is available. Handler - communication channel between
two threads. Handler is associated with Looper. for a given looper we can n number of handlers to
communicate with it from out side world.
75. Can I send a message from threada to threadb, if threadb didnt prepare its
looper?
if thread-a wants to send a message to thread-b, then thread-b's looper should be prepared to retrieve
message send by others.it is also possible with HandlerThread to have inter-thread communication.
76. How to avoid synchronization problems in threads?

The two main reasons to try to avoid synchronize blocks are performance and
protecting yourself from deadlocks.
Using the synchronize keyword involves performance overhead in setting up the
locks and protecting the synchronized operation. While there is a performance
penalty for calling a synchronized block, there's a much bigger hit that gets taken
when the JVM has to manage resource contention for that block.
The classes in java.util.concurrent.atomic can use machine level atomic instructions
rather than locking, making them much faster than code that would use locks. See
the javadoc for the package for more information on how that works.
Also, as u3050 mentioned, avoiding mutable shared state goes a long way to
preventing the need for synchronization.

77. What is the difference between synchronized block(statement) and synchronized


methods?
A synchronized method locks the monitor associated with the instance of the class
(ie 'this') or the class (if a static method) and prevents others from doing so until
the return from the method. A synchronized block can lock any monitor (you tell it
which) and can have a scope smaller than that of the encolsing method.
Synchronized blocks are prefered if they don't end up equivalent to the entire
scope of the method and/or if they lock something less draconian than the
instance (or class if static).

78. If I want to create a service with one worker thread how to achieve it?
In order to pass data from thread back to a service you will need to do this:
1.Subclass a Handler class inside of your service (call it e.g. a LocalHandler). You
will have to make it static. Override a handleMessage method, it will receive
messages from the thread.
2.Add a Handler argument to your Thread constructor. Instantiate
your LocalHandler class in a service and inject it to your thread via constructor.
3.Save reference to the Handler inside of your thread and use it to send
messages whenever appropriate.

Service Class:
package com.example.app;
import
import
import
import
import
import

android.app.Service;
android.content.Intent;
android.os.Handler;
android.os.IBinder;
android.os.Message;
android.util.Log;

public class ConnectionService extends Service {


protected ConnectionWorker thread;
static class LocalHandler extends Handler {
@Override

public void handleMessage(Message msg) {


Log.d(this.getClass().getName(), "Message received: " + (String) msg.obj);
}
}
protected Handler handler;
@Override
public void onCreate() {
super.onCreate();
// Instantiating overloaded handler.
this.handler = new LocalHandler();
// Creating a connection worker thread instance.
// Not starting it yet.
// Injecting our handler.
this.thread = new ConnectionWorker(this.handler);
Log.d(this.getClass().getName(), "Service created");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(this.getClass().getName(), "Trying to start the service");
// Checking if worker thread is already running.
if (!this.thread.isAlive()) {
Log.d(this.getClass().getName(), "Starting working thread");
// Starting the worker thread.
this.thread.start();
Log.d(this.getClass().getName(), "Service started");
}
}

return Service.START_STICKY;

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
Log.d(this.getClass().getName(), "Stopping thread");
// Stopping the thread.
this.thread.interrupt();
Log.d(this.getClass().getName(), "Stopping service");
super.onDestroy();
}
}

Log.d(this.getClass().getName(), "Service destroyed");

Worker Class (Thread)


package com.example.app;
import
import
import
import

android.os.Handler;
android.os.Message;
android.os.SystemClock;
android.util.Log;

public class ConnectionWorker extends Thread {


// Reference to service's handler.
protected Handler handler;
public ConnectionWorker(Handler handler) {
super(ConnectionWorker.class.getName());

// Saving injected reference.


this.handler = handler;

@Override
public void run() {
super.run();
Log.d(this.getClass().getName(), "Thread started");
// Doing the work indefinitely.
while (true) {
if (this.isInterrupted()) {
// Terminating this method when thread is interrupted.
return;
}
Log.d(this.getClass().getName(), "Doing some work for 3 seconds...");
// Sending a message back to the service via handler.
Message message = this.handler.obtainMessage();
message.obj = "Waiting for 3 seconds";
this.handler.sendMessage(message);
SystemClock.sleep(3 * 1000);
}

79. How to create multi threaded service?


Create a service with creating thread in onStartCommand. Or simply use asynctask in the service.

80. How to create a service with threads and that updates ui?
Since updating UI from other thread directly is not possible, communicate with Main UI thread for
the UI updates
Description : Android follows singled threaded UI model, i.e other threads should not touch UI
with out taking permission of Main UI thread. If other threads wants to touch UI, communicate it to
Main thread. Many ways are there to achieve it, use 1. RunOnUiThread() 2. use Handlers to
communicate to main thread 3. Use AsyncTask and update ui from onPre or onPost or onProgress ..
81. What will happen if you start a service that does heavy functionality without
starting a thread?
may,lead,to,anr,application,not,responding,error,some,times,but,that,is,applicable,if,your,application
having atleast one activity since that activity will run in UI thread
Since android gives only one thread per application, default all activities will run in that thread. but
service also performs long running operations in the background, it is not suggestible to run service
also in the same thread which may hang your activities which lead to ANR.
82. What is the UI response time limit in android. (I.E with in how many seconds
main thread has to respond for user actions?)
5sec
If user touches your activity, and if your program doesn't respond to user events with in 5 seconds,
android will not tolerate it and it force closes your application. this error is called as ANR
(Application Not Responding).
83. What is the time limit of a broadcast receiver, what will happen if it crosses that
time limit?
10 sec
Broad cast Receiver is a component that responds to system wide broad cast announcements. It acts
as gateway to other components of our application. It is not supposed to do long running operation,
it has to do its operation in 10 seconds maximum.
84. What is the difference between sendbroadcast(),sendorderedbroadcast(),
sendstickybroadcast() ?
sendbroadcast() - normal broadcast, but we can set priority as well.
sendorderedbroadcast() - we can set priority, and set result. can block broadcasts as well.
In the ordered broadcast you can predict the order of broadcast receiver using priority in the intent_
Filter.
1.If the priority is same for two receivers then order cannot be predicted.
2.In the ordered broadcast you can also pass data between two receivers.
3.You can also abort the broadcast anywhere in between the receivers.
sendstickybroadcast() - intent passed with this will be stick for future users who are registering
through code (dynamic receivers). When somebody sends a sticky broadcast using send
stickyBroadcast(in); then that broadcast will be available for the future users who are using dynamic
receivers. This broadcast will be available for only Dynamic Broadcast rx who are coming in future.
Eg for stickybroadcast is - BATTERY LOW.

85. If I want to start an activity that gives a response, what is the function I need to
use to start that activity?
startActivityForResult(Intent intent) is the function to use to start an activity, which returns some
result to you on finishing itself.
Start Activity for Result():
We will use this function if we are expecting some result from child activity.
Start Activity for result will take two parameters:
1.Intent.
2.Integer Request code (it is a integer constant)
Returning Results form ChildActivity:
If you want to return success to the parent activity then use below functions.
setResult(RESULT_OK); and then finish();
Once you set the result then you have to immediately call finish function.
To return failure:
setResult(RESULT_CANCELED); and then finish();
In case if child activity crashes due to some reason then it will automatically pass RESULT_
CANCELED.
How to catch the results from the child in the parent activity:
For this we have to implement a function called onActivityResult() in parent activity.
OnActivityResult() function has 3 paramaters
1.Request code
2.Result code
3.Intent.
86. If I startactivityforresult() and the child activity gets crashed what is the result
code obtained by the parent?
RESULT_CANCELED
87. In case of low memory if android closes a service forcefully, then will it restart
automatically or user has to start it?
It will never be restarted again by Android if programmer has not returned START_NOT_STICKY
from onStartCommand()
Description : If android has stopped service with out user's knowledge, then it is the responsibility
of android to restart it. But this rule will not be applicable if programmer returns
START_NOT_STICKY from onStartCommand().
88. What are the various return values of onstartcommand() , and when to use what?
START_STICKY - in case if android stops our service forcefully, then restart service by sending
intent null.
START_NOT_STICKY - in case if android stops our service forcefully, then don't restart service,
until user restarts it.
START_REDELIVER_INTENT - in case if android stops our service forcefully, then restart service
by re-sending the intent.

89. Lets say my service supports both starting a service and binding a service, and
currently two persons have started my service and one person is binding to my service.
After 5 minutes person who bound to my service, unbinds it.And other person stops
my service, now is my service running in memory or got moved out from memory?
Service is dead and moved out of memory
Description : Even if one client says stopService(), then service will be dead and moved out of
memory if there are no binded connections are no other startService() requests pending to be
processed.
90. What is empty process and what is its priority? When android will use this
concept?
Empty process- an app which is destroyed and still in the memory.
Description : Empty process - is an application which user is frequently visiting and closing.
(Which resides in memory even after killing). To launch frequently visited app fastly, even after
destroying that app, it will be still in memory so that loading time will be reduced and user feels
more comfortable. That is called as empty process. its priority is 5 (Empty_Process). this is the last
and least priority of an application or a process. When android device goes out of memory, to
reclaim some memory android will start killing all the processes starting with least priority process.
Empty process is the most susceptible process to be killed in case of low memory.
91. How does android achieves seamlessness. What is the meaning of seamlessness?
by handling onSaveInstanceState. Seamlessness means uninterrupted flow of application
by handling configuration changes
by handling low memory scenarios,
Description: seamlessness means un-interrupted flow of an application. No matter what is
happening to your application, user should not feel that disturbance. these disturbances may happen
in case of low memory, and configuration changes where android will and recreate the activity. but
these changes should not be visible to the user and should not disturb user. this can be done by
handling these conditions in onSaveInstantnceState() in all activities
92. What is the difference between menus and dialogs?
menus are designed using xml, they will not change so frequently
dialogs are built using code as they frequently change the content.
Description:Menus are designed using xml, because menus will not change so frequently. You can
build menus using code also when ever required. But it is not recommended to completely build
menus using code.Dialogs are built using code because dialog content will frequently change
93. How many kinds of menus are there in android?
SubMenu, OptionsMenu, ContextMenu
94. How many kinds of dialogues are there in android?
1. AlertDialog - This is the most common form of any dialog, which will contain title, text, and
maximum 3 buttons. There in this 4 types of it - normal alert dialog, items alert dialog, single

choice, & multi choice alert dialog.


2. ProgressDialog. - This is to show progress bar in the dialog box.
3. DatePickerDialog - This is to show date to pick.
4. Time picker dialog - This is to show time to pick.
95. I want to design one application where I take username, password and connect to
the gmail and show the status of login to the user. Now how to design this application?
How many components will be there?
To access user name, pw & to show login status in dialog
we need - one Activity with dialog. To connect to Gmail server we need - one Service, with one
thread.
96. What is the use of httpclient class?
httpclient has a function execute(), which can execute httprequests(get/post) and returns response
from server.
eg: HttpGet get = new HttpGet("http://google.com");
HttpClient c = getDefaultHttpClient(); c.execute(get);
HttpClient can also handle
1. Cookies
2. Authentication
3. Connection management to the server
97. What is the difference between httpget() and httppost() methods, when to use
what?
httpget() - use it when we want to get some information from an URL of a server. httppost() - use it
when we want to post some infromation to a server mentioned by URL from mobile. eg: Use
HttpGet, if you want to get google.com page. Use HttpGet if you want to get all employee details
from server. eg: Use HttpPost, if you want to post some data like posting email to gmail server, or
posting a blog to blog server.
98. What does httpclient.execute() return?
on executing a request (httpget/ httppost), httpclient.execute will return httpresponse which will
contain httpentity(which is the actual response from the server).
99. What are static variables stored in memory segments?
100. If I want to secure my preference file from other activities in my
app, then should I use getpreferences() or getsharedpreferences()?
Use getPreferences(), but its not guaranteed to be protected as it will be stored with the name of
Activity.
Description : getPreferences(0) - will open or create a preference file with out giving a name
specifically. By default preference file name will be the current Activity name. if some one knows
this, any once can access getPreference() file using that activity name.
getSharedPreferences("name",0) - will open or create a preference file with the given name. If you
want to create a preference file with a specific name then use this function. If you want multiple

preference files for you activity, then also you can use this function.
Note: preferences file will be with .xml extension stored in data/data/preferences folder.
101. I want to store huge structured data in my app that is private to my
application, now should I use preferences [or] files [or] sqlite [or] content provider?
Storing your data in a database is one good way to persist your data, but there's a caveat in Androiddatabases created in Android are visible only to the application that created them. That is to say, a
SQLite database created on Android by one application is usable only by that application, not by
other applications.
SharedPreferences is used for just that, storing user preferences shared application-wide. You

can use it, for example, to store a user's username, or perhaps some options he or she has
configured in your app in which you want to remember.

Shared preferences can only store key-value pairings whilst an SQLite database is much more
flexible. So shared preferences are particularly useful for storing user preferences, e.g. should the
app display notifications etc. Whilst an SQLite database is useful for just about anything.
102. My application has only a service, and my service performs heavy
lift functionality to connect to internet and fetch data, now should I create a thread or
not? If so why?
No need to create a new thread in Service as it is not required in this scenario. Because service runs
in the main thread. Since our app doesn't have any activities, so its OK to run service in main
thread. ANR error will occur only if activities and services runs in same thread.
103. I want to write a game where snake is moving in all the directions
of screen randomly, now should I use existing android views or should use canvas?
Which is better?
Using canvas
104. Can I have more than one thread in my service? How to achieve
this?
Services are possible with single thread and multiple threads also. If you want multi threaded
service, then write thread creation logic in onStartCommand() because this function will be called
every time some one starts the service. if you want single threaded service then create thread in
onCreate() of service class. Multi threaded services are also possible with AsyncTasks.
105. When lcd goes off, what is the life cycle function gets called in
activity?
When lcd goes off, activity will be moved to onPause() state. This is a special case.
106. When a new activity comes on top of your activity, what is the life
cycle function that gets executed.
When new activity comes on top of an existing activity, then existing activity will move to invisible
state by calling onPause() -> then -> onStop. If top activity is transparent or doesn't occupy

complete screen, then below activity's onStop() will not be called.


107. When a dialog is displayed on top of your activity, is your activity
in foreground state or visible state?
When a dialog comes on top of an existing activity, then existing activity will move to partially
invisible state by calling onPause().
108. When your activity is in stopped state, is it still in memory or not?
when onStop() is called, then activity is still in memory and all its states and variables are intact.
109. When your activity is destroyed, will it be in memory or moved out
of it?
Generally after calling onDestroy(), app will be removed from memory. But there is an exception
for this rule. If user is visiting an app very frequently then it has to be loaded into memory very
frequently. to avoid this over head for the system, android may choose to keep that app in memory
even after onDestroy(). This is called "empty process". Process which is killed but still in memory.
110. I started messaging app > composer activity > gallery > camera
> press home button. Now which state camera activity is in?
When we press home button any activity, that will be moved to back ground state (invisible state),
so it calls onStop() on that activity
111. Continuation to above question, now If I launch gmail application
will it create a new task or is it part of old messaging task?

112. Can I have more than one application in a given task?


task is a collection of apps that user traverse when performing some task. eg: while sending
message, he starts with messaging application, and may move to gallery or camera to attach some
photo that message. in this scenario messaging and gallery are two different apps. but for user he is
doing single task only.
113. Can I have more than one process in a given task?
Apps and process is same. Task is a collection of one or more applications. App means process, so
task can contain multiple processes.
114. Do all the activities and services of my application run in a single
process?
Activities, services and other components of an applications runs in single process. there can be
some situations where we can allow a component of application to run in a different process. but
this is possible only if user id of those two different processes are same.
115. Do all components of my application run in same thread?

each application will have one process and one main thread created by system, by default. So by
default all the components of an android application runs in Main thread (UI thread)
116. How to pass data from activity to service?
There are many ways to do it. one straight forward way is pass data in intent-putextras, and say
startService() with that intent. one more way is store it in common database or shared preference
file and access it through both activity and service
117. How to access progress bar from a service?
all UI controlling has to be done in activity to reduce side effects. if a services wants to touch UI,
send a broadcast from service which triggers a receiver in activity which is dynamically registered
in activity for communication. from that receiver you can touch UI since it is inner class of it.
118. What is the difference between intent and intentfilter?
Intent : is a message passing mechanism between components of android, except for content
provider. you can use intents to pass data from one component to other component. you can also use
intents to start one component from other component.
eg: you can start an activity by using intents.
intent-filter : tells about the capabilities of that component. it tells what kind of implicit intents that
component can handle. intent-filters are counter parts for intents.
119. What is the difference between contentprovider and content
resolver?
DB, Files, preferences are stored in private memory of application which cannot be accessed by
outside applications.content provider is used to share this private data with other applications.
Where as contentresolver is used to communicate with content provider from client application. As
of now there is no support for shared preferences with content provider.
120. What is the difference between cursor & contentvalues ?
ContentValues is a name value pair, used to insert or update values into database tables.
ContentValues object will be passed to SQLiteDataBase objects insert() and update() functions.
Where as Cursor is a temporary buffer area which stores results from a SQLiteDataBase query.
121. What is Bundle? What does it contain in oncreate() of your
activity?
Bundle is a data holder, which holds data to be passed between activities. In case of forceful closing
of an activity, android will save all its UI states and transient states so that they can be used to
restore the activity's states later. This saved states will be passed via Bundle in onCreate() function
to restore its states once android recreates a killed activity. EG: this will happen in case of low
memory or configuration changes like rotating the phone.
onSaveInstanceState(): This function will be called by aAndroidAndroidndroid before ompause
or after onpause if aAndroidAndroidndroid is forcefully killing your activity. In this function we
have to save all your activity states.

onRestoreInstanceState(): This function will be called after onStart.


122. When an activity is being started with an intent action
MY_ACTION, how can I see that action in triggered component(activity)?
If you are defining a custom Intent action that should be internal to your application, then you
do not need to define it in your Manifest file.
For example, in an app, I am using the LocalBroadcastManager as part of a dispatcher pattern
implementation. I would register a BroadcastReceiver implementation this way:
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.android.MY_ACTION");
LocalBroadcastManager.getInstance(context).registerReceiver(receiver, filter);

Then when I run the following code, my receiver will receive the locally broadcasted Intent:
Intent intent = new Intent();
intent.setAction("com.example.android.MY_ACTION");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

123. How to get contact number from contacts content provider?


//First get the all basic details from basic table of contacts
Cursor c1 = this.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
c1.moveToNext(); //move to first row
String id = c1.getString(c1.getColumnIndex(Contacts._ID)); //get its id
//now based on that id, you can retrive phone details from other table.
Cursor cur = this.getContentResolver().
query(CommonDataKinds.Phone.CONTENT_URI,
null,
CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
cur.moveToNext();
String number = cur.getString(cur.getColumnIndex(
CommonDataKinds.Phone.NUMBER));
124. How to take an image from gallery and if no images available in
gallery I should be able to take picture from camera and return that picture to my
activity?
private static final int SELECT_PICTURE = 1;
// ...
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(

);

Intent.EXTRA_INITIAL_INTENTS,
new Intent[] { takePhotoIntent }

startActivityForResult(chooserIntent, SELECT_PICTURE);

125. What is the difference between linear layout and relative layout?
linear layout - arranges child element in either vertical or horizontal fashion.
Relative layout - arranges child elements in relative to each other. I
mportant properties of Relative Layout:
1. android:below 2. android:above 3. android:toRightof 4. android:toLeftof
126. How many kinds of linear layouts are there?
Horizontal and vertical
127. What is dp [or] dip means ?
px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
1 Inch = 2.54 centimeters
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
Dp/Dip
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These
units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel
will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts
both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference.
It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen
density and user's preference.

128. What is importance of gravity attribute in the views?


android:gravity sets the gravity of the content of the View its used on.
android:layout_gravity sets the gravity of the View or Layout in its parent.
129. What is adapter? What is adapter design pattern?
bridge between source and adapter views

130. What is adapterview? How many adapter views are available in


android?
any view that takes input from adapter is called as adapter view. eg:listview, gallery, spinner,
gridview, etc..
131. Can you tell me some list adapters?
Array adapter,base adapter cursor adapter,expadaple list adapter
132. Can I give cursor to an array adapter?
No because array adapter takes - lists (arraylists); cursor adapter takes - cursor which is returned
from database tables upon querying.
133. What is custom adapter, when should I use it. what are the
mandatory functions I need to implement in custom adapter?
getView, getItem, getItemId, and getCount are the mandatory functions that have to be implemented
in Custom Adapter.
134. What is the class that I need to extend to create my own adapter?

To create a own custom adapter, one can extend BaseAdapter, or can extend any of the existing
concrete adapters like ArrayAdapter, SimpleCursorAdatper etc.. Note: we can also extend or
implement other adapter interfaces, but it is not so useful. Generally extending BaseAdapter is
enough to create our own custom adapter.
135. What is the android compilation and execution process/ cycle?
java file -- will be given to -- java compiler -- to generate -- .class file. all .class files -- will be given
to -- dx tool -- to generate single -- dex file dex file -- will be given to -- dvm -- to generate -- final
machine code. final machine code -- will be given to -- CPU -- to execute.
136. What is adb? What is the command to install one application using
adb command prompt?

137. What is the debugging procedures available in android?

138. How will you analyze a crash, how will fix using logcat?
after crash logcat will contain file name,exception name along with line number where it has
crashed.
139. What is a break point and how to watch variables while debugging?
break point breaks the execution. To see value either you can put cursor on it or right click on
variables and add to watch
140. What is ddms? What are the various components in ddms?
Android provides a debugging tool called the Dalvik Debug Monitor Server (DDMS).
i) DDMS provides port-forwarding services.
ii) Screen capture on the device.
iii) Thread and heap information on the device.
iv) Logcat.
v) Process.
vi) Radio state information.
vii) Incoming call and SMS spoofing, location data spoofing, and more.

141. What is the difference between started service and binded service?
Started service - is used to do some long running operation in the back ground. it will be alive in
memory even if the person who started it is no longer in memory. either it itself can stop or some
other also can stop it. generally services will not have UI. it is used to some back ground
functionalities like sending SMS, downloading files, etc..
Binded service- is like a client server architecture where clients can request to binded service to
execute some function and return the result. started services will not return results generally. since
data flow happens from service to client, there should be communication channel in the case of
binded services.
142. How to achieve bind service using IPC?
1. create a service & implement onCreate(), onBind(), onUnbind(), onDestroy()
2. create .aidl file with interface functions.
3. implement auto generated Binder stub class in service.
4. return object to this stub class from onBind()
143. How will I know if a client is connected to a service or not?
144. I want to access a functionality from one application to other

application, then should I use content provider or startservice or bind service?


145. I want to access data of another application in my application, now
do I need to implement content providers in my application or other application has to
implement it?
other applicationwhich is sharing data has to implement it.
146. What is the difference between local variables, instance variables,
and class variables?
Local Variables:
is Declared Inside a Method.
Must be Initialized before use.
It won't compile if not Initialized.
Instance Variables:
is Declared Inside a Class.
Initialization is not compulsory.
Contains Default Value. (For int its 0, for float its 0.0f, etc.)
Compiles even if not Initialized
class variables
The class variables must have the keyword static as the modifier and are declared inside a class body
butoutside of any method bodies.
Only one copy of class variables are created from the point the class is loaded into the JVM until the the class
is unloaded, regardless of the number of object instances that are created from that class.
If one object instance of that class changes the value of a class variable then all the other instances see
thesame changed value.

147. What is anonymous class? Where to use it?


Anonymous classes are those for which there is no class name, but body will exist. You can create
anonymous classes by extending a base class or by implementing an interface. Eg: for anonymous
class is button click listeners in Android.
148. What is singleton class, where to use it? show with one example
how to use it?
It is a design pattern, where a class is designed in such a way that, there is only object for that class.
This can be achieved in many ways, general way of implementation is by making the constructor as
private, and creating and returning object through a static method of that class.
149. If I want to listen to my phone locations, what all the things I need
to use? Is it better to use network providers or gps providers?
gps
150. My phone dont have network signal and satellite signal, now is
there any way to fetch my last location where signal was available?
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use
LocationManager.GPS_PROVIDER

Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); This


should give your last known location. Use GPS_PROVIDER for better results.
151. I have some data available in docs.google server, and I want to
display it in tabular fashion, tell me the sequence of steps to achieve this?
152. If I want to start some heavy weight functionalities that takes lot of
battery power like starting animation or starting camera, should I do it in oncreate() or
onstart() or onresume() of my activity? And where should I disable it?
If I want to start some heavy weight functionalities that takes lot of
battery power like starting animation or starting camera, should I do it in oncreate() or
onstart() or onresume() of my activity? And where should I disable it?
Since heavy weight functions take too much of battery power, better do it just before your activity is
ready to take user events. so do it in onResume().Since heavy weight functions take too much of
battery power, better do it just before your activity is ready to take user events. so do it in
onResume().
153. Why you should not do heavy functionality in onresume and
onpause() of your activity?
154. What things I can do in onrestart() of my activity?
onRestart () 1.Called after onStop() when the current activity is being re-displayed to the user
2.It will be followed by onStart() and then onResume()
3.If you have deactivated any cursor in onStop(), call managedQuery() again.
4.Derived classes must call through to the super class's implementation of this method. If they do
not, an exception will be thrown.
155. What is
the life cycle
of a service?

The system calls this method when another component, such as an activity,
onStartComman

requests that the service be started, by calling startService(). If you implement

d()

this method, it is your responsibility to stop the service when its work is done,
by calling stopSelf() or stopService() methods.
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must

onBind()

provide an interface that clients use to communicate with the service, by


returning an IBinder object. You must always implement this method, but if
you don't want to allow binding, then you should returnnull.

onUnbind()

The system calls this method when all clients have disconnected from a
particular interface published by the service.
The system calls this method when new clients have connected to the service,

onRebind()

after it had previously been notified that all had disconnected in


its onUnbind(Intent).
The system calls this method when the service is first created

onCreate()

usingonStartCommand() or onBind(). This call is required to perform onetime set-up.


The system calls this method when the service is no longer used and is being

onDestroy()

destroyed. Your service should implement this to clean up any resources such
as threads, registered listeners, receivers, etc.

156. What is the life cycle of a broadcast receiver?


there is only one function in broad cast receiver, that is onReceive(). Broadcast receiver's life will
start before calling onReceive() method, and once control comes out of onReceive() method, then it
will be killed.
157. What is the life cycle of a content provider?
Content Providers don't have a particular lifecycle, there is not much you can do to control it. The
framework manages the creation and destruction of a Content Provider(process).
When external clients or components outside of the process make a request to the Content Provider,
that request is processed in a thread from a thread pool of the process the provider resides in. And
when there are no more requests the process can be reclaimed if there are no more active
components (activity, service) in that process. But that is a decision Android takes.

158. What is the life cycle of a thread?

1) New
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
159. What is the life cycle of your application process?
(application)Process will be loaded into memory before loading first component of the application,
and will be killed after destroying all components.But if user is visiting that application very
frequently, then android might not kill the process at all to optimize the loading time of that
application.
If user is visiting an application very frequently, then its better to retain that application in the
memory rather than killing it. Reason for this is, next time when user visits the same application no
need to load that application into memory, as it is already in memory. So user will feel happy for
showing application very quickly. This is called as empty process(application).
160. How to kill one activity?
Activity can be killed programatically in two ways. finish() or finishActivity(int requestcode).
finish() - can be used by an activity to kill itself. finishActivity(int requestcode) - Force finish
another activity that you had previously started with startActivityForResult(Intent intent, int
requestcode); This function will let the parent activity to kill the child activity, which it has started
previously.
161. What is log.d ? where to use log functions?
Log messages are used to debug the program. Log.d() is debug log.
other functions are
Log.i() - informative
Log.e() - error log
Log.w() - warning
log Log.v() - verbose log

162. Draw the life cycle of an activity in case of configuration change?


1 onPause() -> onSaveInstanceState() -> onCreate() -> onStart() -> onRestoreInstanceState() ->
onResume()
2 onPause() -> onSaveInstanceState() -> onStop() -> onDestroy()->onCreate() -> onStart() ->
onRestoreInstanceState() -> onResume()
3.onPause() -> onSaveInstanceState() -> onStop() -> onCreate() -> onStart() ->
onRestoreInstanceState() -> onResume()
Configuration change : is either orientation change(phone rotation), or language settings change. In
case of configuration change, android will forcefully kill your activity and recreates it, unless you
are not handling configuration changes on your own programmatically.
When android kills your activity due to configuration changes, it makes sure that it will definitely
call onPause() and onSaveInstanceState. But there is no guarantee about call onStop and onDestroy.
But android documentation doesn't say that it will not call onStop and onDestroy. it depends.
Life cycle in the case of configuration changes can be any of the option 1, or 2, or 3, based on the
situation. some times it might not kill activity at all if programmer is handling configuration
changes programmatically, which is not a standard way to do.
163. What is the difference between viewgroup and layout?
viewgroup - is invisible container, and abstract class. Layouts are more concrete form of view
groups. view groups derive from views, and layouts derive from view groups.
Eg of layouts are 1.framelayout, 2.relative layout, 3.linear layout, etc..
164. Draw the key event flow in android?
Key events will flow like this: Android system -> Activity -> Layout -> View -> programmer. First
priority will be given programmer written logic, if programmer has written some thing to handle
some key events it will be execute first. From there based on the return statement it will decide to
flow back that key event to parent or not. eg: if programmer choose to block some key say
KEYCODE_0, then for that key code he can say return true; which will block that event and will be
destroyed in programmers function only.
165. When you fire an intent to start with ACTION_CALL , what is the
permission required?
<uses-permission android:name="android.permission.CALL_PHONE" />

166. What are the permissions required to obtain phone locations?


android.permission.ACCESS_FINE_LOCATION - use this if you are using GPS features in your
programming. else android.permission.ACCESS_COARSE_LOCATION - use this if you are
fetching locations based on career network or by using WiFi.
167. How many levels of security available in android?
Android supports 2 levels of security for applications. one at operating system level or kernel level.
other is using <permission> tags in app level.

168. How to achive security to your service programmatically in such a


way that your service should not get triggered from outside applications?
If you don't want to expose your service to outside apps, 3 ways are there. 1. Don't give intent-fiiter
tag, so that outsiders can't specify intent action to trigger your service. or 2. User exported="false"
in service tag, so that outside world cant trigger it. or 3. User local service manager.
169. What are the sequence of tests done to map intent with an intent
filter?
When programmer starts a component by using an intent, to trigger appropriate component android
will perform 3 tests.
1.action test : the action string of intent should match with at least one action string of intent filter.
2.data test : data and data type of intent should match with that of intent filter.
3.category test : all the categories of intent should be there in intent filter. note: In case of implicit
intent starting an activity, then default category will be automatically added to intent.
If there is any component in manifest file with an intent filter which passes all the 3 tests, then
android will trigger that component. Else not. If there are multiple components satisfying that
intent, and if it is not a broadcast receiver, then it will ask user to make a decision.
170. Describe various folders in android project in eclipse?
src
gen
Android version(such as Android 2.2)
assets
res

171. What is raw folder in eclipse project?


This is just like assets folder, but only difference is this folder has to be accessed via R.java file. you
can store any assets like MP3 or other files.
172. Under what thread broad cast receiver will run?
Default every component of android will run in Main thread (UI thread). So broadcast receiver also
runs in main thread by default.
173. If I want to notify something to the user from broadcast receiver,
should I use dialogs or notifications? Why?
Only Activity's can create/show dialogs. So use notifications

174. Can you create a receiver without registering it in manifest file?


We can register receiver dynamically in code.
Description : Every component has to get registered in the manifest file. But there is an exception
for this rule, a broad cast receiver can get registered dynamically in code. Because there may be
some scenarios where we need handle broad casted messages only when our application is running.
If we register it in manifest file statically, then even if our app is not running, it may trigger our

broad cast receiver.


175. If I want to broadcast BATTERY_LOW action, should I use sendbroadcast() or
sendstickybroadcast? Why?
We have to use sendStickyBroadCast() because, logically if battery went down, then this
information has to be available for applications which may run after some time in future.
176. If I want to set an alarm to trigger after two days, how should I
implement it? assume that I may switch off the phone in between.
177. I want to trigger my broadcast receiver as long as my activity is in
memory, else it should not get triggered, how should I achieve this?
178. What is sleep mode? What will happened to CPU once screen light
goes off?
179. How many kinds of wake locks are available, which one to use
when?
180. If I am using full wake lock and user presses screen lights off, what
will happen?
181. When phone is in sleep mode, what are the two components that
will keep running even though phone is in sleep mode?
182. Every day night at 12 o clock I need to post some images to
facebook, in that case I will set repeating alarm for every day night 12 am. But to
upload images I want to start service, how should I do this ?
183. When you start an activity from a notification, will it start as new
task or old task?
184. Why android follows single threaded ui mode? How other threads
can manipulate ui views?
185. What is the purpose of SQLiteOpenHelper?
186. What is the procedure to upgrade database after first release?
187. Show with one example where memory leak possibility in
Android?
188. If I want to write one application for both phones and tablets, what
should I use in my UI?
189. I have a thousands of items in my array, and I want to display it in
listview, what is the most optimized way to achieve this?
190. What is r.java file? What does it contain?
191. Write one application which will get triggered immediately after
booting.
192. What does .apk file contains?
193. How will pass information from one activity to other activity, lets
say pass userid, city, and password to next activity and display it.
Search
Home
Write
Notifications
194. Write code for an xml file having a relative layout with employee
registration form.
195. Get a table information from the database and show it in table UI
format.
196. I have thousands of columns and thousands of rows to display it in
UI tabular format, how should I show it this dynamically growing UI. Should I load all
in single shot or any optimization can be done?

197. When to use String, StringBuffer, & StringBuilder?


198. What is String constant pool? What is the difference between below
two statements?
i. Which is preferred way to use?
ii. String str1 = hi;
iii. String str2 = new String(hi);
199. If I want to share a String between two threads, and none of threads
are modifying my String which class I have to use?
200. If I want to use my String within only one thread which is
modifying my String, then which class I have to use? Similarly if I want to my string to
be changed by more than one thread then which class I have to use?
201. How does String class look like? What is final class meant for?
How will you implement your own String class?
202. What is immutable object? How is it different from immutable
class?
203. Depict one example for immutable class in java framework?
204. How will you write a class in such a way that it should generate
immutable objects?
205. Does String class uses character array internally in its
implementation?
206. What is the difference between char & Character classes? Which
one is value type and which one is ref type?
207. What is the meaning of pass by reference? If I have an integer array
and if I pass that array name to a function, is it pass by value or pass by reference?
208. I want to use array in my program which has to grow dynamically,
in that case should I use Array [or] ArrayList [or] Vector? What is the difference
between arraylist and vector? Which one of them is not part of collections framework
of JAVA?
209. I want to use dynamically growing array shared between two
threads, should I use arraylist or vector?
210. I want to store values of my employees in a data structure using
java collections framework in such a way that I should be able to read, write, modify &
delete them very fastly. Which datastructure should I use ? arraylist [or] linkedlist [or]
hashsets [or] hashmap ?
211. Write a program in such a way that Thread1 will print from 11000
& Upvote Thread2 15
will Downvote print from 10001. Comment Thread1 Share
should sleep for 1 second at every 100th
location. Thread2 should interrupt thread1 once thread2 reaches 500.
212. How will you stop a thread, which is currently running?
213. If Thread1 interrputs Thread2, how Thread2 should handle it?
(Generally how threads should handle interruptions?) how will thread2 know that other
threads are interrupting it?
214. What is interrupted exception? Which functions will throw this
exception? How to handle it?
215. Assume that two threads t1, & t2 are running simultaneously in
single core CPU. How does t2 will request OS that it wants to wait till t1 is finished?
216. I want to implement threads in my program, should I extend Thread
class or implement Runnable interface? Which one is better, justify your answer in
terms of design.
217. What will happen if you return from run() function of your thread?

218. What is the difference between checked & unchecked exceptions?


Which one programmer should handle?
219. arrayIndexOutOfBounds, NullPointerException,
FileNotFoundException, ArithmeticException, InterruptedException, IOError,
IOException. In this list which exceptions programmer has to handler compulsorily?
Categorize above exception list into ERROR/ RUNTIME EXCEPTION/ REST
categories.
220. Assume that I am writing a function which likely to throw checked
exception, in that case if I dont handle it will compiler throw any error?
221. How one should handle checked exceptions? Mention 2 ways to
handle it.
222. I am writing a function where it is likely that checked exception
may come, I want to handle it in my function and I want to pass that exception to my
parent caller also. How do I achieve it?
223. What is difference between throw, throws?
224. Can I write a try block without catch statement?
225. What is difference between final, finally, & finalize.
226. Will java ensure that finalize will be executed all the time
immediately after object is destroyed? How to mandate it?
227. What is 9 patch image, how is it different from .png images? Why
we have to use this in android? How will it help in the scalability of an image for
various screens?
228. What is the difference between synchronized method and
synchronized block? If I have a huge function where only two lines of code is
modifying a shared object then should I use synchronized block or method?
229. Implement insertion sort, binary search, and heap sort.
230. How many ways a server can communicate (Send data) to a mobile
application? Which is fastest way json or xml?
231. What is JSONArray & JSONObject. Show this with one example
by requesting one URL using HTTP, which gives JSON object.
232. Name some sites which extensively use JSON in communicating
their data with clients.
233. What is the permission you need to take for fetching GPS locations,
& reading contacts. Where will you have to write permissions in manifest file?
234. How will you display data base information in a table kind of
architecture in android? Which view will you use?
235. How many kinds of adapterviews, and adapters available in
android?
236. What is notifydatasetchanged() function meant for?
237. Take data base cursor of employee (eno, ename, salary) into a
cursor, fill into a list view where each item should have a check box also, how will you
implement it in android?
238. What is the difference between constructor and static block. Can I
initialize static variables in constructor?
239. I want to use a private variable of ClassA in classB directly
without using any function. How to achieve this?
240. I want to create a class in such a way that nobody should be able to
create object for that class except me. How to do it?
241. Can I access instance variables in a static function? Can I access
static function /variable from an instance method?
242. Why is multiple inheritance of classes not allowed in java? If I
http://androidquestions.quora.com/250-Android-Interview-Questions

6/7
8/24/2015
(5) 250 Android Interview Questions - Android interview questions - Freshers & Experienced
- Quora
want to get functions of ClassA & ClassB into classC. how do I design this
program?
243. Does java allow multiple inheritance of interfaces? Can one
interface extend other interface ? when should I extend interface from other interface?
244. What is the difference between over loading and over riding?
245. Can I over ride base class constructor in derived class?
246. Can I over load a constructor?
247. How does default constructor look like? What super() call does in a
constructor?
248. Why does base class constructor gets executed before executing
derived class constructor? Justify this with appropriate example?
249. How will you achieve dynamic polymorphism using over riding?
Justify usage by taking some example (note: use clientserver example)
250. Why overloading is static polymorphism, justify your answer?
251. What is the difference between static/compile time linking &
dynamic/run time linking? Are static functions dynamically linked?
252. Show one IsA relation with one example.
253. Show one HasA relation with one example.

You might also like