Android 253 QSN and Answer
Android 253 QSN and Answer
Android 253 QSN and Answer
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.
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" />
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);
}
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.
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.
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.
import
import
import
import
import
android.content.Context;
android.graphics.Canvas;
android.graphics.Typeface;
android.util.AttributeSet;
android.widget.TextView;
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
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:
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.
Note : To pass data between activities, services, and receivers use only Bundles. Don'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.
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;
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();
}
}
android.os.Handler;
android.os.Message;
android.os.SystemClock;
android.util.Log;
@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);
}
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
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
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.
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);
);
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.
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?
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
The system calls this method when another component, such as an activity,
onStartComman
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()
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()
onCreate()
onDestroy()
destroyed. Your service should implement this to clean up any resources such
as threads, registered listeners, receivers, etc.
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
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.