Android Interview Questions: 1. Draw architecture diagram of android framework.
2. Which kernel(Operating system) is used in android Ans : Linux Kernel !. In which language android "ramework is written Ans: Java #. What does $%& stand "or Ans: Dalvik virtual Machine '. Why $%& why not %& Ans: Conceptually, there is little diference rom an application level between a DVM and a JVM. Architecturally, Architecturally, there is a major diference diference between the reisterbased reisterbased DVM and and the stac!"based JVM. #oth use a VM code model. $owever, the DVM uses reisterbased opcodes that are comparable to the reister"based reister"based bytecode instructions that most o the taret platorms already e%ecute. e%ecute. &his includes architectures architectures such as those available rom A'M and M()* and the %+"compatible architectures rom (ntel, AMD, and V(A &echnoloies. -oole developed Android and chose DVM or several reasons. irst, irst, there were licensin
issues with most JVMs. /e%t, the DVM should be more e0cient in terms o memory usae and perormance on a reister"based machine. DVM is also supposed to be more e0cient when runnin multiple instances o the DVM. Applications are iven their own instance. $ence, multiple active applications re1uire multiple DVM instances. 2i!e most Java implementations, the DVM has an automatic arbae collector. collector.
. Which layer does $%& sits Ans: library layer *. What is the latest version o" android +an you tell me what is the new concepts ans: lollyo !" design#$atery $acku#notification#erformance added in this version% ,. -plain li"e cycle o" activity
/. I" I have a 0roadcast receiver that updates my 1I "reuently3 then where should I register that 0roadcast receiver in my activity li"e cycle "unctions Ans : on&tart'( function will $e called )ust $efore your activity will $e made visi$le to the user. user. &o any thing that affects !" has to $e registered in on&tart'( function. 45. +an I save all my data0se ta0les updations in on6top() o" activity I" not eplain why and also eplain where should I save d0 ta0les Ans: *o# $ecause on&to'( may not $e called in some situations. situations. Descrition : "n case of low memory or configuration changes# there is a chance that android may
force+kill your alication $efore reaching on&to'(. on,ause'( is the only function that will $e called with out fail $efore killing the alication. so save all ersistent data like D- ta$les in on,ause'( only. *ote : e can/t save all data$ase ta$les in on&ave"nstance&tate# $ecause that function will not $e called if user resses $ack $utton. 11. What is di""erence 0etween persistent data and transient data3 give one eample. Also tell me which activity li"e cycle "unction I need to use to save them Ans:'0( ,ersistent data is ermanent data that we store# eg in data$ase ta$les# and transient data is logical data that we use in rogramming logic. Descrition : ,ersistent data means ermanent# and transient means temorary. "f it is not necessary to save the data ermanently and you only want to save the state of the !"# you can use the onSaveInstanceState onSaveInstanceState event event to store the state in a Bundle Bundle.. his should not $e relied uon to save data since the event event is not art of the activity lifecycle and is only triggered $y the !" when the activity needs to $e recreated or is sent to the $ackground# $ut not when it is destroyed ermanently : it is meant for storing tr ansient view states. &ome of the data is already saved $y the Android &DK# $ut you may need to save extra information# for examle if you have custom controls. hen the user navigates $ack $ack to the activity and the state of the !" needs to $e restored# the $undle containing the state information is accessi$le from the onRestoreInstanceState event raised if the activity was still in memory# memory# or from the onCreate onCreate event event raised if the activity was recycled and needs to $e recreated. 42. What will happen i" I remove super.oncreate() "rom oncreate() "unction o" activity 2very Activity Activity you make is started through a se3uence of method calls. on0reate'( is the first of these calls. 2ach and every one of your Activities extends extends android.a.Activity either directly or $y su$classing another su$class of Activity. "n Java# when you inherit from a class# you can override its methods to run your own code in them. A very common common examle of this is the overriding of the to&tring'( method when extending )ava.lang.4$)ect. hen we override a method# we have the otion of comletely relacing the method in our class# or of extending the existing arent class/ method. -y calling suer suer.on0reate'save .on0reate'saved"nstance&tate(5# d"nstance&tate(5# you tell the Dalvik 6M to run your code in addition to the existing code in the on0reate'( of the arent class. "f you leave out this line# then only your code is run. he existing code is ignored comletely. 7owever## you must include this suer call in your method# $ecause if you don/t then 7owever the on0reate'( code in Activity is never run# and your a will run into all sorts of ro$lem like having no 0ontext assigned to the Activity 'though you/ll hit a &uer*ot0alled2xcetion $efore you have a chance to figure out that you have no context(. "n short# Android/s own classes can $e incredi$ly comlex. he code in the framework classes handles stuff like !" drawing# house cleaning and m aintaining the Activity and alication lifecycles.suer calls allow develoers to run this comlex code $ehind the scenes# while still roviding a good level of a$straction for our own as.
4!. What is the purpose " super.oncreate() Ans : 8o to 3sn 19 1. &how me how does intentfilter of main activity looks like% hat is the action and what is the category% 3activity android4name56com.e%ample.project.MainActivity6 android4name5 android4label5 android4label 567strin8app9name6 : 3intent";lter: 3action android4name android4name5 56android.intent.action.MA(/6 8:
3cateory android4name android4name5 56android.intent.cateory.2A
Descrition : action.MA"* + says this activity is the main activity 'starting oint( for this alication. category.LA!*072; category.LA!*072; + says this activity should aear in the home screen/s launcher. launcher. •
•
•
action : Declares the intent action acceted# in the name attri$ute. he value must $e the literal string value of of an action# action# not the class class constant. constant. category: Declares the intent category acceted# in the name attri$ute. he value must $e the literal string value of an action# not the class constant. android:name he name of the action. &ome standard actions are defined in the "ntent class as AC&(>/9strin constants. o o assign one of these actions to this attri$ute# reend 6android.intent.action.6 to the string that follows AC&(>/9 .
4'. What is the importance o" version code and version name attri0utes in mani"est "ile it tells your alications version num$er and name. "t will $e used when you want to udate your a in google lay store Descrition : 6ersion no and name will $e useful when you uload some alication to lay store and wanted to udate it. hen you are ugrading your alication then you can increment the version num$er so that users of your alication will get notification on their hones a$out the latest udates availa$le. 1<. 0an one alication have more than on manifest file% 4*. +an I create activity without ml "ile =es# with the excetion of the manifest and erhas some theme declarations '"/m not sure if there are u$lic Java e3uivalents for everything we can set u via themes(. "s it a good idea% 7eavens# no. he oint $ehind the resource system is to allow Android to transarently hand you the roer resources needed $y the device at the resent moment# $ased on $oth ermanent device characteristics 'e.g.# screen density( and transient device characteristics 'e.g.# ortrait vs. landscae orientation(. o avoid the resources# you will have to go through a $unch of if statements to determine which hunk of Java code to run# detecting all these things $y hand. his gets significantly more comlicated once you take into account changes in Android itself# as new configuration changes and values get added# making it difficult for you to suort everything you need to in a $ackwards+ comati$le way. Along the way# you will lose all tool t ool suort 'drag+and+dro 8!" $uilding# M44D26 &tudio/s string resource assistants# etc.(# outside of lain Java editing and de$ugging. =ou seem to $e lacing your own ersonal technical inclinations ahead of all other considerations. "f this is some small ersonal ro)ect# that may $e a fine attitude. "f you are creating code to $e develoed and>or maintained maintained $y others over time# though# you need to factor in the needs of those other develoers# and they may $e much more oen to ?ML than are you.
4,. 7ow to create ui without using ml "ile3 show with one eample on how to create activity with a linear layout and with two 0uttons and without having ml "ile public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override onCreate(Bundle savedInstanceState savedInstanceState { public void onCreate(Bundle super.onCreate(savedInstanceState!
// creatin" #inear#ayout #inear#ayout lin#ayout $ new #inear#ayout(this! // s%ecifyin" vertical orientation lin#ayout.setOrientation(#inear#ayout.&')ICA#! // creatin" #ayoutara+s #ayoutara+s lin#ayoutara+ $ new #ayoutara+s (#ayoutara+s.MA)C,-A') #ayoutara+s.MA)C,-A')! // set #inear#ayout as a root ele+ent of the screen setContent&iew(lin#ayout lin#ayoutara+! #ayoutara+s l%&iew $ new #ayoutara+s(#ayoutara+s.0A-CO)') #ayoutara+s.0A-CO)')! )e1t&iew tv $ new )e1t&iew(this! tv.set)e1t(2)e1t&iew2! tv.set#ayoutara+s(l%&iew! lin#ayout.add&iew(tv!
Button 3tn $ new Button(this! 3tn.set)e1t(2Button2! lin#ayout.add&iew(3tn l%&iew!
#inear#ayout.#ayoutara+s leftMar"inara+s $ new #inear#ayout.#ayoutara+s( #ayoutara+s.0A-CO)') #ayoutara+s.0A-CO)')! leftMar"inara+s.leftMar"in $ 45! Button 3tn6 $ new Button(this ! 3tn6.set)e1t(2Button62! lin#ayout.add&iew(3tn6 leftMar"inara+s!
#inear#ayout.#ayoutara+s ri"ht7ravityara+s $ new #inear#ayout.#ayoutara+s( #ayoutara+s.0A-CO)') #ayoutara+s.0A-CO)')! ri"ht7ravityara+s."ravity $ 7ravity.I7,)! Button 3tn8 $ new Button(this ! 3tn8.set)e1t(2Button82! lin#ayout.add&iew(3tn8 ri"ht7ravityara+s!
9 9
4/. 8ive me two eamples o" con"iguration changes in phone fliing the hone key$oard on language settings change $escription : configuration changes include: rotating the hone# having virtual keyad on# and changing language settings in settings. 25. What is the mandatory li"e cycle "unction that will get called in case o" con"iguration 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.
24. +an I save large images downloaded "rom internet in onsaveinstancestate() on&ave"nstance&tate'( function has to $e used for saving small o$)ects 'transient states(. "f we want
to save large o$)ects use on;etain*on0onfiguration"nstance'( function. 4r else we can make that image as static# so that the image will $e loaded only once. More documentation : on&ave"nstance&tate'( function has to $e used for saving small o$)ects# not for heavy o$)ects. "f you want to save heavy images on hone rotation# then use any of $elow techni3ues: 1. "f you want to save large o$)ects use on;etain*on0onfiguration"nstance'( function. 9. 4r else we can make that image as static# so that the image will $e loaded only once. Meaning: 4n downloading an image from network# make it ointed $y a static varia$le. "f user rotates the hone# since android kills that activity and recreates it# )ust ut a if condition check if that static varia$le is not null# then only download again. As you know static varia$les will $e created only once# it will not download again.
22. What is the di""erence 0etween this 9 getapplicationcontet() which one to use when his oints to current context# alication context oints to entire rocess. if your context is of entire life time of rocess then use a context# else this. Descrition : this ointer always oints to current class o$)ect# a context will oint to entire rocess. there is only one a context. if you want to use some control whose life time is through out your alication life time then go for a context# else use this ointer 'activity context(. getApplication+ontet() + ;eturns the context for all activities running in alication. getase+ontet() + "f you want to access 0ontext from another context within alication you can access. get+ontet() + ;eturns the context view only current running activity.
2!. -very application will have 0y de"ault one thread ;rue or "alse Default android will allocate one main thread called as '!" thread( to every rocess or alication.
2#. What is A<= (application not responding) What is the reason "or this pro0lem and what is the solution "or that pro0lem A*; + will occur if we are doing any other heavy functionality along with !" in single Main hread."f two heavy functionalities haen in single thread# it will delay resonse to user actions# which may irritate user# and hence sto your rocess. &olution + ;un only !" comonents in Main hread. 9@. Main thread will have a looer # tr ue or false% only handler threads will have looers . $escription : Main hread is a handler thread# so it will have looer ena$led. *ormal threads looer will $e in disa$led mode# where as handler threads will have their looers ena$led. $ut if we want we can reare looers for normal threads also.
2. y de"ault a given process will have how many threads Who will create those threads 1 main thread created $y android system $escription : &ince every rocess re3uires a thread to run with 0,!# $y default android system will create one main thread for every alication 2*. What will happen i" I remove oncreate() 9 onstart() "rom activity Will it run nothing will haen it will run erfectly $escription : "t is a standard# that rogrammer has to imlement corresonding life cycles methods of activity $ased on the functionality suorted. -ut one can ski those functions if rogrammer wish to.
2,. +an I have an activity without 1I yes# if it is doing some functionality with out !" Descrition : 8enerally every activity will have !" '!ser "nterface( screens. -ut if rogrammer wants he can omit !" and do some $ackground functionality with an Activity. *ote: o do $ackground functionality its $etter to use service than an activity with out !". "t makes more sense.
2/. What is the di""erence 0etween intent3 sticky intent3 pending intent intent + is a message assing mechanism $etween comonents of android excet for 0ontent ,rovider5 &ticky "ntent + &ticks with android# for future $road cast listeners5 ,ending "ntent + ill $e used when some one wants to fire an intent in future and may $e at that time that a is not alive. $escription : intent + is a message assing mechanism $etween comonents of android# excet for 0ontent ,rovider. =ou can use intent to start any comonent. &ticky "ntent + &ticks with android# for future $road cast listeners. or examle if -A2;=BL4 event occurs then that intent will $e stick with android so that if any future user re3uested for -A2;BL4# it will $e fired5 ,ending "ntent + "f you want some one to erform any "ntent oeration at future oint of time on $ehalf of you# then we will use ,ending "ntent. 2g: -ooking a ticket at late night when your alication is not running. "n this scenario we will create a ending intent to start a service which can $ook tickets at late night and hand it over to Alarm Manager to fire it at that time.
!5. What is the di""erence 0etween implicit intent and eplicit intent3 give one eample "mlicit intent + "ntent with out target comonent name5 2xlicit intent + "ntent with target comonent name. $escription : "mlicit intent + "ntent with out target comonent name5 2xlicit intent + "ntent with target comonent name. 28: if we want to start a new screen or activity with in our alication# then we clearly know what is that activity name $ecause $oth activities are in same alication. "n such cases we will use exlicit intent. Assume that we want to launch 8allery activity from our alication# then we don/t know exact name of that gallery activity $ecause gallery is a different alication# in that case we will use imlicit intent with some matching actions. 2g for 2xlicit intent: Intent in = new Intent(getApplicationContext(), SecondScreen.class); >>target comonent name startActivity(in); *ote: 2xlicit intents are secifically used to start other comonents of same alication. 2g for "mlicit intent: Intent in = new Intent(); >>no target comonent name in.setAction(Intent.ACTION!"TCONT"NT); in.setType(#i$age%); startActivity(in); *ote: "licit intents are secifically used to start comonents of other alications. !4. 7ow many components are there in an intent "ntent can have a.action# $.data and its tye# c.category# d. extras# e.arget 0omonent name# f. some extra flags.
!2. +an I give more than one action in a given intent "ntent can have maximum one action# $ut it is not mandatory. some times it can have C actions also 'in case of exlicit intent(. &o an intent can have C+1 actions.
!!. +an I give more than one category in a given intent =es. =ou can have C or n num$er of categories in intent Descrition : !nlike actions# an intent can choose to have C or n num$er of categories.
!#. +reate an intent to start calling a num0er >42!#'? "ntent in new "ntent'(5 in.setAction'"ntent.A0"4*B0ALL(5 in.setData'!ri.arse'Etel:19F@E((5 startActivity'in(5
!'. what is the importance o" putetras in intent 7ow is it di""erent "rom setdata() any way 0oth are passing data only 3 so in that case what is the di""erence setData'( + is to ass data on which to take action. ut2xtra'( + is to send extra information a$out this intent. $escription : setData'( + is to ass data on which to take action. ut2xtra'( + is to send extra information a$out this intent. 28: if one is starting an activity to erform A0"4*B0ALL# then he has to set num$er in setData'(. this function will contain on which data target comonent has to take action. if one want to ass extra details also# then only use ut2xtra'(.
!. What is the di""erence 0etween thread and service
*ervice is li!e an Activity but has no interace. )robably i you want to etch the weather or e%ample you won?t create a blan! activity or it, or this you will use a *ervice. A &hread is a &hread, probably you already !now it rom other part. @ou need to !now that you cannot update <( rom a &hread. @ou need to use a $andler or this, but read urther. An Async&as! is an intellient &hread that is advised to be used. (ntellient as it can help with it?s methods, and there are two methods that run on <( thread, which is ood to update <( components.
•
•
•
!*. +an 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. $escription : &ervice is a comonent that erforms some oeration in the $ackground with out having !". -ut it doesn/t mean that it will have searate thread to do it. -y default if rogrammer doesn/t rovide any thread for the service# then it runs in Main !" thread. &ince it is not good ractice to run Activity G &ervices in single thread# it is suggesti$le to have searate thread for the service# excet in few cases like where a given alication is not having any activity in it. FH. "f " want to touch ui from another thread can " touch directly% hat will haen if " do so%
FI. 7ow to achieve inter thread communication% Inter-thread communication or Co-operation is all about allowin synchronied threads to communicate with each other.
Cooperation B(nter"thread communication is a mechanism in which a thread is paused runnin in its critical section and another thread is allowed to enter Bor loc! in the same critical section to be e%ecuted.(t is implemented by ollowin methods o Object class4 waitB Causes current thread to release the loc! and wait until either another thread
•
invo!es the notiyB method or the notiyAllB method or this object, or a speci;ed amount o time has elapsed. /otiyB
•
a!es up a sinle thread that is waitin on this object?s monitor. ( any
threads are waitin on this object, one o them is chosen to be awa!ened. /otiyAllB a!es up all threads that are waitin on this object?s monitor.
•
#5. What is the di""erence 0etween thread and handler thread
&hreads are eneric processin tas!s that can do most thins, but one thin they cannot do is update the <(. $andlers on the other hand are bac!round threads that allow you to communicate with the <( thread Bupdate the <(. *o or e%ample show a toast or a update a proress bar via a messae B'unnable posted to a handler but you can?t i you start this runnable as a thread. ith handler you can also have thins li!e MessaeEueuin, schedulin and repeatin. ( am yet to encounter a situation where ( needed a thread in android. ( mostly use a combination o Async&as!s and $andlers. $andlers or the aorementioned tas!s. Async&as!s or download8 data etchin and pollin etc. @ou can read the developer article here 6)ainless &hreadin6 or more threadin in android. Correction4 =ach $andler instance is associated with a sinle thread and that thread?s messae 1ueue. &hey are not threads in their own behal.
#4. what will happen i" I 0ind a service "rom a 0road cast receiver3 is there any pro0lem *o# 4ne should not $ind a service from -roadcast receiver. $ecause# $roadcast receivers will have a time limit of 1C seconds. esta$lishing connection to a service may take more time.
$escription:4ne should not $ind a service from -roadcast receiver. he reason is $roadcast receivers are light weight comonents# where it has to finish its functionality with in not more than 1C seconds maximum. 2lse android may forcefully kill your receiver. -inding 'esta$lishing connection to( a service may take more than 1C seconds in some worst cases# that/s why android won/t allow it. ;ules for -roadcast ;eceivers: 1.-roadcast receivers will not have any !"'mostly( and it will have only $ackground logic. 9.-roadcast receivers will have the maximum time limit of 1C sec to finish its functionality otherwise it will crash. F.=ou should not do long running oerations or asynchronous oerations in the receiver. 2xamle: a. ,rearing &D card. $. !loading > Downloading files from internet. c. 0reating D$ files. d. -inding to services .Do not show dialog to the user in $roadcast receiver. 'this is asynchronous oeration( @.=ou can use toast or *otifications. <.Dont write any heavy functionalities.
#2. +an I start a service "rom a 0roadcast receiver =es htts:>>$log.nra$oy.com>9C1>1C>use+$roadcast+receiver+$ackground+services+android> F. 7ow to start a service with foreground riority% startoreground 'int id# *otification notification(# use this function in on0reate'( of your service. $escription : 8enerally services will run in $ackground# which is of Frd riority. if you feel that the service is critical for user# then you can increase its riority $y making it foreground service. !se function startoreground 'int id# *otification notification(# in on0reate'( of your service to make this service as foreground service. oreground services will $e treated with highest riority# so android will ensure it will not kill these services even in case of low memory situations. 2g: M,F layer service is a foreground service.
##. What is the di""erence 0etween 0roadcast receiver and a service3 where most o" the cases 0oth will not have any 1I3 in that case which one I should use -roadcast;eceiver + is like gateway for other comonents# can do small $ack ground functionality with in 1C seconds. &ervices + can do long running oeration in the $ackground with out having !"# and no time limit for it.$ut $oth receiver and service $oth can interact with !" if they want to. -roadcast ;eceivers have time limit of 1C seconds# and they resond to $roadcasted messages. $escription : -roadcast;eceiver + is like gateway for other comonents# can do small $ack ground functionality with in 1C seconds. &ervices + can do long running oeration in the $ackground with out having !"# and no time limit for it.$ut $oth receiver and service $oth can interact with !" if they want to. services will not have time limit of 1C seconds# receivers resond to $roadcasted
#'. I" I start an activity with implicit intent3 and there is no matching intent"ilter then what will happen it will throw run time excetion + activity*otound2xcetion# and crashes if it is not handled roerly. $escription : for startActivity'intent(# if there are no matching target comonents or activities# then it will throw run time excetion + Activity*otound2xcetion# and will crash the rogram if this excetion is not handled. <. I" I send a 0road cast with implicit intent3 and there is no matching intent"ilter then what will happen *othing will haen# $ut it will not launch any receiver. $escription : !nlike startActivity'( and start&ervice'(5 send-roadcast'( will not throw any run time excetion. "f there are no target comonents availa$le for this $roadcast it will kee 3uiet. "t is $ecause in case of activity and service# action is yet to $e erformed $ut in case of $roadcast;eceiver action is already over and we are )ust informing it to every one.
#*. Write a 0roadcast receiver that gets triggered once phone 0oot is done uses+ermission android:nameEandroid.ermission.;202"62B-44B04M,L22DEN>uses+ ermissionN receiver android:nameE-roadcast;eceiverEN intent+filterN action android:nameEandroid.intent.action.-44B04M,L22DEN>actionN >intent+filterN >receiverN H. hat will haen if " dont ass any action in an imlicit intent# will it trigger any comonent% #/. +an I start a content provider using an intent not ossi$le. !sing intent you can/t trigger a content rovider. $ecause# we use content resolver to communicate with content rovider $escription : "ntents will $e used to communicate or start comonents of android. 4nly excetion is content rovider. =ou can start an activity# service# and a $roadcast receiver using intent $ut not content rovider. or content rovider we have to use content resolver to communicate.
'5. I have one intent "ilter without any action3 then can I trigger this component "rom outside o" this application *o# with out any action no one can trigger or start that comonent from outside world. Descrition : ithout any action in the intent filter# it is not ossi$le to start that comonent from outside world. intent filters# action will $e considered only for imlicit intents. *ote: =ou can exlicit intents only with in the alication.
'4. +an I have more than one action in my intent"ilter intent filters can have C or more num$er of actions. -ut if that comonent has only one intent+filter with C actions# then that comonent can $e triggered using only exlicit intents. a given intent+filter can have more than one action $ecause# a given comonent can do more than one action. 28: notead can erform two actions A0"4*B6"2 G A0"4*B2D" on an existing note ad file.
@9. 0an " have more than one category in my intentfilter%
'!. +an I have etras in my intent"ilter intent+filter tag will not have extra tag. it has only action# category# and data tags. extra tag will not $e used while erforming tests for intent resolution.
'#. I want to start something in the 0ackground in my activity3 should I use thread or should I start service Why "f that $ackground functionality is co+related with activity# then use thread. else launch it in a new service with thread in the service. $escription : "t always deends on the re3uirement. if the $ackground functionality is related or tightly couled with activity# then use thread. $ut if you want some thing to do in $ackground irresective of whether activity is alive or not# then go for service+with thread.
''. I" I crate a thread in my activity and i" I stop my activity what will happen to that thread3 will it 0e alive or dead it will $e alive# $ut its riority will $e least comared to thread in a service. $escription : once a thread is created# it will run indeendently of who has created until the work given to that thread is finished. $ut in case of low memory scenarios a thread created $y activity and which is running in the $ackground will have more susceti$ility of $eing killed $y android system. More worse is android can not recreate the thread which was killed $ecause of low memory. $ut if that thread was in service# then chances of getting killed $y android due to low memory may $e less than revious situation. even if android system kills the thread# again it will start the service when memory resources are availa$le and service can re+initiate that killed thread.
'. I" I start a service "rom my activity and i" I stop my activity what will happen to that service3 will it 0e alive or dead service will $e kee running in the $ackground# $ut it can sto itself when the work given to it is done. 4r others also can kill that service using sto&ervice'(# or android also can kill the service forcefully in case of low memory scenarios.
$escription : service will $e kee running in the $ackground# even if the activity which has created is no more alive.-ut it can sto itself when the work given to it is done. 4r others also can kill that service using sto&ervice'(# or android also can kill the service forcefully in case of low memory scenarios. @O. 7ow many ways are there to kill a service% @H. "f " want my service to allow $inding# then what is the function that " need to imlement in my service class% @I. 0an " create a customiPed textview%
import android.content.Conte%tF import android.raphics.CanvasF import android.raphics. &ypeaceF import android.util.Attribute*etF import android.widet. &e%tViewF public class ont&e%tView e%tends &e%tView G public ont&e%tViewBConte%t conte%t G superBconte%tF &ypeace ace5 &ypeace.createromAssetBconte%t.etAssetsB, 6$elvetica9/eue.tt6F this.set&ypeaceBaceF H public ont&e%tViewBConte%t conte%t, Attribute*et attrs G superBconte%t, attrsF &ypeace ace5 &ypeace.createromAssetBconte%t.etAssetsB, 6$elvetica9/eue.tt6F this.set&ypeaceBaceF H public ont&e%tViewBConte%t conte%t, Attribute*et attrs, int de*tyle G superBconte%t, attrs, de*tyleF &ypeace ace5 &ypeace.createromAssetBconte%t.etAssetsB, 6$elvetica9/eue.tt6F this.set&ypeaceBaceF H protected void onDraw BCanvas canvas G super.onDrawBcanvasF H H 3com.util.ont&e%tView android4id567Iid8te%tView6 android4layout9width56wrap9content6 android4layout9heiht56wrap9content6 android4te%t567strin8account(no&e%t6 android4te%tColor56KLLL6 android4te%t*ie56+dp6 8:
. What is the de"ault shared pre"erence "ile name o" an activity ActivitynameN.xml Descrition : -y default if rogrammer don/t give any name to shared reference# then activity name will $e taken as shared reference file with .xml extension.
*. What is the di""erence 0etween task3 process3 application3 and thread
)rocess4 A process is an instance o a computer proram that is bein e%ecuted. (t contains the proram code and its current activity. Dependin on the operatin system B>*, a process may be made up o multiple threads o e%ecution that e%ecute instructions concurrently. )rocess"based multitas!in enables you to run the Java compiler at the same time that you are usin a te%t editor. (n employin multiple
processes with a sinle C)<,conte%t switchin between various memory conte%t is used. =ach process has a complete set o its own variables.
&hread4 A thread o e%ecution results rom a or! o a computer proram into two or more concurrently runnin tas!s. &he implementation o threads and processes difers rom one operatin system to another, but in most cases, a thread is contained inside a process. Multiple threads can e%ist within the same process and share resources such as memory, while diferent processes do not share these resources. =%ample o threads in same process is automatic spell chec! and automatic savin o a ;le while writin. &hreads are basically processes that run in the same memory conte%t. &hreads may share the same data while e%ecution.
&as!4 A tas! is a set o proram instructions that are loaded in memory. ,. $oes android support multi tasking I" yes eplain how to start a new task when you are already running one task Android supports multitas!in at app level also. press home button on current tas! which will move it to bac!round and then you can start new tas! rom launcher. there is one more way to start a new tas! by usin 2A-9/=9&A*N when you are startin a new activity.
/. $oes android support multi threading
@es, Android supports Multithreadin. &he most preerred way o implementin itBother than &hread )ool and =%ecutor is Async&as! Async&asc allows you to implement do(n#ac!roundB, where your thread can cran! away at its tas!. &his is similar to the unctionality you?d et rom &hread. &he real maic happens when you override on)re=%ecuteB and on)ost=%ecuteB , which are both executed on the UI thread. &his should !eep you rom ettin messaes about your Activity not bein attached. *5. What is the mechanism used 0y android "or Interprocesscommunication ",0 means "nter rocess communication : here two alications or rocesses will communicate with each other $y assing some data $etween them. &ince android is meant for em$edded and small devices# we should not use serialiPation f or ",0# rather we can use -"*D2;s which internally uses arcels. arcel is a sort of light weight serialiPation $y using shared memory concet. here are many differences $etween -inder ",0 and &erialiPation ",0: 1. &erialiPation is very heavy to use in em$edded devices# communication will $e very slow. 9. -inders uses ,arcels to make ",0 very fast. F. -inders internally uses &hared memory concet which uses less memory while sharing data $etween two rocesses. -ottom line : -inders uses less memory# and 3uite fast as it uses arcels. &erialiPation is very heavy # takes time to send and receive data# and also it takes more memory comared to $inders.
*ote : o ass data $etween activities# services# and receivers use only -undles. DonGQFI5t go for either serialiPation or $inders.
*4. 7ow 0inder is di""erent "rom seriali@ation -inder uses shared memory concet to do "nter rocess communication $escription : &erialiPation and -inders are $oth ",0 mechanisms how to rocesses will communicate. &erialiPation is very heavy as it has to coy hole data and transmit to other rocess through channel. -ut -inders are light weight where $oth the rocesses will share or communicate the data using a shared memory concet. what ever the data has to $e shared it will $e ket in a common shared memory and $oth rocess/s can access that memory to make communication faster.
*2. 7ow seriali@ation di""er "rom parcel ,arcels are used in -inders. e use arcels for only ",0s# for normal serialiPation we use serialiPa$les. $escription : ,arcel is not a general+urose serialiPation mechanism.his class is designed as a high+erformance ",0 transort. used heavily in "-inders. for normal serialiPation concets# use &erialiPa$les. since serialiPa$les are heavy and takes time# we use ,arcels for ",0 in em$edded devices.
*!. I" I have one application with activity3 service3 and contentprovider. ;hen when I run this program how many process3 threads will 0e created Is it possi0le to run these components in more than one process 4ne rocess# one hread# =es it is ossi$le to run in more than one rocess. $escription : -efore loading an alication into ;AM# a rocess will $e created with a thread $y default. 2ven though in Linux# an alication will $e given only one rocess to run all its comonents# it is 3uite ossi$le that comonents of a given alication can run in more than one rocess rovided $oth rocesses have same Linux user id.
*#. What is looper3 message ueue3 and a 7andler Where do you need these components Looer + art of any hread to loo through message 3ueue. Message R + art of any thread# will store incoming messages to this thread. 7andler + communication channel $etween two threads. $escription : Looer + art of any hread to loo through message 3ueue.his will $e used to check if any incoming message has arrived to this thread. 4nly one looer exists for a given thread. 4nly for handler threads this looer will $e activated# for other normal threads this will $e in assive or inactive mode. Message R + art of any thread# will store incoming messages to this thread. or any thread only one message R is availa$le. 7andler + communication channel $etween two threads. 7andler is associated with Looer. for a given looer we can n num$er of handlers to communicate with it from out side world. *'. +an I send a message "rom threada to thread03 i" thread0 didnt prepare its looper if thread+a wants to send a message to thread+$# then thread+$/s looer should $e reared to retrieve message send $y others.it is also ossi$le with 7andlerhread to have inter+thread communication.
*. 7ow to avoid synchroni@ation pro0lems in threads
&he two main reasons to try to avoid synchronie bloc!s are perormance and protectin yoursel rom deadloc!s.
A synchronied method loc!s the monitor associated with the instance o the class Bie ?this? or the class Bi a static method and prevents others rom doin so until the return rom the method. A synchronied bloc! can loc! any monitor Byou tell it which and can have a scope smaller than that o the encolsin method. *ynchronied bloc!s are preered i they don?t end up e1uivalent to the entire scope o the method and8or i they loc! somethin less draconian than the instance Bor class i static. OH. "f " want to create a service with one worker thread how to achieve it%
(n order to pass data rom thread bac! to a service you will need to do this4 .*ubclass a $andler class inside o your service Bcall it e.. a 2ocal$andler. @ou will have to ma!e it static. >verride a handleMessae method, it will receive messaes rom the thread. .Add a $andler arument to your &hread constructor. (nstantiate your 2ocal$andler class in a service and inject it to your thread via constructor. O.*ave reerence to the $andler inside o your thread and use it to send messaes whenever appropriate.
Service Class: pac!ae com.e%ample.appF import android.app.*erviceF import android.content.(ntentF import android.os.$andlerF import android.os.(#inderF import android.os.MessaeF import android.util.2oF public class Connection*ervice e%tends *ervice G protected Connectionor!er threadF static class 2ocal$andler e%tends $andler G 7>verride
public void handleMessaeBMessae ms G 2o.dBthis.etClassB.et/ameB, 6Messae received4 6 I B*trin ms.objF H H protected $andler handlerF 7>verride public void onCreateB G super.onCreateBF 88 (nstantiatin overloaded handler. this.handler 5 new 2ocal$andlerBF 88 Creatin a connection wor!er thread instance. 88 /ot startin it yet. 88 (njectin our handler. this.thread 5 new Connectionor!erBthis.handlerF 2o.dBthis.etClassB.et/ameB, 6*ervice created6F H 7>verride public int on*tartCommandB(ntent intent, int Ras, int start(d G 2o.dBthis.etClassB.et/ameB, 6&ryin to start the service6F 88 Chec!in i wor!er thread is already runnin. i BSthis.thread.isAliveB G 2o.dBthis.etClassB.et/ameB, 6*tartin wor!in thread6F 88 *tartin the wor!er thread. this.thread.startBF 2o.dBthis.etClassB.et/ameB, 6*ervice started6F H return *ervice.*&A'&9*&(CN@F H 7>verride public (#inder on#indB(ntent intent G return nullF H 7>verride public void onDestroyB G 2o.dBthis.etClassB.et/ameB, 6*toppin thread6F 88 *toppin the thread. this.thread.interruptBF 2o.dBthis.etClassB.et/ameB, 6*toppin service6F super.onDestroyBF 2o.dBthis.etClassB.et/ameB, 6*ervice destroyed6F H H
Worker Class (hread! pac!ae com.e%ample.appF import android.os.$andlerF import android.os.MessaeF import android.os.*ystemCloc!F import android.util.2oF public class Connectionor!er e%tends &hread G 88 'eerence to service?s handler. protected $andler handlerF public Connectionor!erB$andler handler G superBConnectionor!er.class.et/ameBF 88 *avin injected reerence. this.handler 5 handlerF H 7>verride public void runB G super.runBF 2o.dBthis.etClassB.et/ameB, 6&hread started6F 88 Doin the wor! inde;nitely. while Btrue G i Bthis.is(nterruptedB G 88 &erminatin this method when thread is interrupted. returnF H 2o.dBthis.etClassB.et/ameB, 6Doin some wor! or O seconds...6F 88 *endin a messae bac! to the service via handler. Messae messae 5 this.handler.obtainMessaeBF messae.obj 5 6aitin or O seconds6F this.handler.sendMessaeBmessaeF *ystemCloc!.sleepBO T PPPF H H H
*/. 7ow to create multi threaded service 0reate a service with creating thread in on&tart0ommand. 4r simly use asynctask in the service.
,5. 7ow to create a service with threads and that updates ui &ince udating !" from other thread directly is not ossi$le# communicate with Main !" thread for the !" udates $escription : Android follows singled threaded !" model# i.e other threads should not touch !" with out taking ermission of Main !" thread. "f other threads wants to touch !"# communicate it to Main thread. Many ways are there to achieve it# use 1. ;un4n!ihread'( 9. use 7andlers to communicate to main thread F. !se Asyncask and udate ui from on,re or on,ost or on,rogress ..
,4. What will happen i" you start a service that does heavy "unctionality without starting a thread may#lead#to#anr#alication#not#resonding#error#some#times#$ut#that#is#alica$le#if#your#alication having atleast one activity since that activity will run in !" thread &ince android gives only one thread er alication# default all activities will run in that thread. $ut service also erforms long running oerations in the $ackground# it is not suggesti$le to run service also in the same thread which may hang your activities which lead to A*;.
,2. What is the 1I response time limit in android. (I.- with in how many seconds main thread has to respond "or user actions) @sec "f user touches your activity# and if your rogram doesn/t resond to user events with in @ seconds# android will not tolerate it and it force closes your alication. this error is called as A*; 'Alication *ot ;esonding(.
,!. What is the time limit o" a 0roadcast receiver3 what will happen i" it crosses that time limit 1C sec -road cast ;eceiver is a comonent that resonds to system wide $road cast announcements. "t acts as gateway to other comonents of our alication. "t is not suosed to do long running oeration# it has to do its oeration in 1C seconds maximum. ,#. What is the di""erence 0etween send0roadcast()3sendordered0roadcast()3 sendsticky0roadcast() send$roadcast'( + normal $roadcast# $ut we can set riority as well. sendordered$roadcast'( + we can set riority# and set result. can $lock $roadcasts as well. "n the ordered $roadcast you can redict the order of $roadcast receiver using riority in the intentB ilter. 1."f the riority is same for two receivers then order cannot $e redicted. 9."n the ordered $roadcast you can also ass data $etween two receivers. F.=ou can also a$ort the $roadcast anywhere in $etween the receivers. sendsticky$roadcast'( + intent assed with this will $e stick for future users who are registering through code 'dynamic receivers(. hen some$ody sends a sticky $roadcast using send sticky-roadcast'in(5 then that $roadcast will $e availa$le for the future users who are using dynamic receivers. his $roadcast will $e availa$le for only Dynamic -roadcast rx who are coming in future. 2g for sticky$roadcast is + -A2;= L4.
,'. I" I want to start an activity that gives a response3 what is the "unction I need to use to start that activity
startActivityor;esult'"ntent intent( is the function to use to start an activity# which returns some result to you on finishing itself. &tart Activity for ;esult'(: e will use this function if we are execting some result from child activity. &tart Activity for result will take two arameters: 1."ntent. 9."nteger ;e3uest code 'it is a integer constant( ;eturning ;esults form 0hildActivity: "f you want to return success to the arent activity then use $elow functions. set;esult';2&!LB4K(5 and then finish'(5 4nce you set the result then you have to immediately call finish function. o return failure: set;esult';2&!LB0A*02L2D(5 and then finish'(5 "n case if child activity crashes due to some reason then it will automatically ass ;2&!LB 0A*02L2D. 7ow to catch the results from the child in the arent activity: or this we have to imlement a function called onActivity;esult'SS( in arent activity. 4nActivity;esult'( function has F aramaters 1.;e3uest code 9.;esult code F."ntent.
,. I" I startactivity"orresult() and the child activity gets crashed what is the result code o0tained 0y the parent ;2&!LB0A*02L2D
,*. In case o" low memory i" android closes a service "orce"ully3 then will it restart automatically or user has to start it "t will never $e restarted again $y Android if rogrammer has not returned &A;B*4B&"0K= from on&tart0ommand'( $escription : "f android has stoed service with out user/s knowledge# then it is the resonsi$ility of android to restart it. -ut this rule will not $e alica$le if rogrammer returns &A;B*4B&"0K= from on&tart0ommand'(. ,,. What are the various return values o" onstartcommand() 3 and when to use what &A;B&"0K= + in case if android stos our service forcefully# then restart service $y sending intent null. &A;B*4B&"0K= + in case if android stos our service forcefully# then don/t restart service# until user restarts it. &A;B;2D2L"62;B"*2* + in case if android stos our service forcefully# then restart service $y re+sending the intent.
,/. Bets say my service supports 0oth starting a service and 0inding a service3 and currently two persons have started my service and one person is 0inding to my service. A"ter ' minutes person who 0ound to my service3 un0inds it.And other person stops my service3 now is my service running in memory or got moved out "rom memory &ervice is dead and moved out of memory $escription : 2ven if one client says sto&ervice'(# then service will $e dead and moved out of memory if there are no $inded connections are no other start&ervice'( re3uests ending to $e rocessed.
/5. What is empty process and what is its priority When android will use this concept 2mty rocess+ an a which is destroyed and still in the memory. $escription : 2mty rocess + is an alication which user is fre3uently visiting and closing. 'hich resides in memory even after killing(. o launch fre3uently visited a fastly# even after destroying that a# it will $e still in memory so that loading time will $e reduced and user feels more comforta$le. hat is called as emty rocess. its riority is @ '2mtyB,rocess(. this is the last and least riority of an alication or a rocess. hen android device goes out of memory# to reclaim some memory android will start killing all the rocesses starting with least riority rocess. 2mty rocess is the most susceti$le rocess to $e killed in case of low memory.
/4. 7ow does android achieves seamlessness. What is the meaning o" seamlessness $y handling on&ave"nstance&tate. &eamlessness means uninterruted flow of alication $y handling configuration changes • $y handling low memory scenarios# • $escription: seamlessness means un+interruted flow of an alication. *o matter what is haening to your alication# user should not feel that distur$ance. these distur$ances may haen in case of low memory# and configuration changes where android will and recreate the activity. $ut these changes should not $e visi$le to the user and should not distur$ user. this can $e done $y handling these conditions in on&ave"nstantnce&tate'( in all activities •
/2. What is the di""erence 0etween menus and dialogs menus are designed using xml# they will not change so fre3uently dialogs are $uilt using code as they fre3uently change the content. $escription:Menus are designed using xml# $ecause menus will not change so fre3uently. =ou can $uild menus using code also when ever re3uired. -ut it is not recommended to comletely $uild menus using code.Dialogs are $uilt using code $ecause dialog content will fre3uently change
/!. 7ow many kinds o" menus are there in android &u$Menu# 4tionsMenu# 0ontextMenu I. 7ow many kinds of dialogues are there in android%
1. AlertDialog + his is the most common form of any dialog# which will contain title# text# and maximum F $uttons. here in this tyes of it + normal alert dialog# items alert dialog# single
choice# G multi choice alert dialog. 9. ,rogressDialog. + his is to show rogress $ar in the dialog $ox. F. Date,ickerDialog + his is to show date to ick. . ime icker dialog + his is to show time to ick.
/'. I want to design one application where I take username3 password and connect to the gmail and show the status o" login to the user.
/. What is the use o" httpclient class httclient has a function execute'(# which can execute httre3uests'get>ost( and returns resonse from server. eg: 7tt8et get new 7tt8et'Ehtt:>>google.comE(5 7tt0lient c getDefault7tt0lient'(5 c.execute'get(5 7tt0lient can also handle 1. 0ookies 9. Authentication F. 0onnection management to the server
/*. What is the di""erence 0etween httpget() and httppost() methods3 when to use what httget'( + use it when we want to get some information from an !;L of a server. httost'( + use it when we want to ost some infromation to a server mentioned $y !;L from mo$ile. eg: !se 7tt8et# if you want to get google.com age. !se 7tt8et if you want to get all emloyee details from server. eg: !se 7tt,ost# if you want to ost some data like osting email to gmail server# or osting a $log to $log server.
/,. What does httpclient.eecute() return on executing a re3uest 'httget> httost(# httclient.execute will return httresonse which will contain httentity'which is the actual resonse from the server(.
//. What are static varia0les stored in memory segments 455. I" I want to secure my pre"erence "ile "rom other activities in my app3 then should I use getpre"erences() or getsharedpre"erences() !se get,references'(# $ut its not guaranteed to $e rotected as it will $e stored with the name of Activity. $escription : get,references'C( + will oen or create a reference file with out giving a name secifically. -y default reference file name will $e the current Activity name. if some one knows this# any once can access get,reference'( file using t hat activity name. get&hared,references'EnameE#C( + will oen or create a reference file with the given name. "f you want to create a reference file with a secific name then use this function. "f you want multile
reference files for you activity# then also you can use this function.
data>references folder. 1C1. " want to store huge structured data in my a that is rivate to my alication# now should " use references TorU files TorU s3lite TorU content rovider% &toring your data in a data$ase is one good way to ersist your data# $ut there/s a caveat in Android+ data$ases created in Android are visi$le only to the alication that created them. hat is to say# a &RLite data$ase created on Android $y one alication is usa$le only $y that alication# not $y other alications. *hared)reerences is used for !ust that, storing user preferences shared application"wide. #ou
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.
&hared references can only store key+value airings whilst an &RLite data$ase is much more flexi$le. &o shared references are articularly useful for storing user references# e.g. should the a dislay notifications etc. hilst an &RLite data$ase is useful for )ust a$out anything.
452. &y application has only a service3 and my service per"orms heavy li"t "unctionality to connect to internet and "etch data3 now should I create a thread or not I" so why *o need to create a new thread in &ervice as it is not re3uired in this scenario. -ecause service runs in the main thread. &ince our a doesn/t have any activities# so its 4K to run service in main thread. A*; error will occur only if activities and services runs in same thread.
45!. I want to write a game where snake is moving in all the directions o" screen randomly3 now should I use eisting android views or should use canvas Which is 0etter !sing canvas
45#. +an I have more than one thread in my service 7ow to achieve this &ervices are ossi$le with single thread and multile threads also. "f you want multi threaded service# then write thread creation logic in on&tart0ommand'( $ecause this function will $e called every time some one starts the service. if you want single threaded service then create thread in on0reate'( of service class. Multi threaded services are also ossi$le with Asyncasks.
45'. When lcd goes o""3 what is the li"e cycle "unction gets called in activity hen lcd goes off# activity will $e moved to on,ause'( state. his is a secial case.
45. When a new activity comes on top o" your activity3 what is the li"e cycle "unction that gets eecuted.
hen new activity comes on to of an existing activity# then existing activity will move to invisi$le state $y calling on,ause'( +N then +N on&to. "f to activity is transarent or doesn/t occuy
comlete screen# then $elow activity/s on&to'( will not $e called.
45*. When a dialog is displayed on top o" your activity3 is your activity in "oreground state or visi0le state hen a dialog comes on to of an existing activity# then existing activity will move to artially invisi$le state $y calling on,ause'(.
45,. When your activity is in stopped state3 is it still in memory or not when on&to'( is called# then activity is still in memory and all its states and varia$les are intact.
45/. When your activity is destroyed3 will it 0e in memory or moved out o" it 8enerally after calling onDestroy'(# a will $e removed from memory. -ut there is an excetion for this rule. "f user is visiting an a very fre3uently then it has to $e loaded into memory very fre3uently. to avoid this over head for the system# android may choose to kee that a in memory even after onDestroy'(. his is called E emty rocessE. ,rocess which is killed $ut still in memory.
445. I started messaging app CD composer activity D gallery D camera D press home 0utton.
444. +ontinuation to a0ove uestion3 now I" I launch gmail application will it create a new task or is it part o" old messaging task
442. +an I have more than one application in a given task task is a collection of as that user traverse when erforming some task. eg: while sending message# he starts with messaging alication# and may move to gallery or camera to attach some hoto that message. in this scenario messaging and gallery are two different as. $ut for user he is doing single task only.
44!. +an I have more than one process in a given task
As and rocess is same. ask is a collection of one or more alications. A means rocess# so task can contain multile rocesses.
44#. $o all the activities and services o" my application run in a single process Activities# services and other comonents of an alications runs in single rocess. there can $e some situations where we can allow a comonent of alication to run in a different rocess. $ut this is ossi$le only if user id of those two different rocesses are same.
44'. $o all components o" my application run in same thread
each alication will have one rocess and one main thread created $y system# $y default. &o $y default all the comonents of an android alication runs in Main thread '!" thread(
44. 7ow to pass data "rom activity to service here are many ways to do it. one straight forward way is ass data in intent+utextras# and say start&ervice'( with that intent. one more way is store it in common data$ase or shared reference file and access it through $oth activity and service
44*. 7ow to access progress 0ar "rom a service all !" controlling has to $e done in activity to reduce side effects. if a services wants to touch !"# send a $roadcast from service which triggers a receiver in activity which is dynamically registered in activity for communication. from that receiver you can touch !" since it is inner class of it.
44,. What is the di""erence 0etween intent and intent"ilter "ntent : is a message assing mechanism $etween comonents of android# excet for content rovider. you can use intents to ass data from one comonent to other comonent. you can also use intents to start one comonent from other comonent. eg: you can start an activity $y using intents. intent+filter : tells a$out the caa$ilities of that comonent. it tells what kind of imlicit intents that comonent can handle. intent+filters are counter arts f or intents.
44/. What is the di""erence 0etween contentprovider and content resolver D-# iles# references are stored in rivate memory of alication which cannot $e accessed $y outside alications.content rovider is used to share this rivate data with other alications. here as contentresolver is used to communicate with content rovider from client alication. As of now there is no suort for shared references with content rovider.
425. What is the di""erence 0etween cursor 9 contentvalues 0ontent6alues is a name value air# used to insert or udate values into data$ase ta$les. 0ontent6alues o$)ect will $e assed to &RLiteData-ase o$)ects insert'( and udate'( functions. here as 0ursor is a temorary $uffer area which stores results from a &RLiteData-ase 3uery.
424. What is undle What does it contain in oncreate() o" your activity -undle is a data holder# which holds data to $e assed $etween activities. "n case of forceful closing of an activity# android will save all its !" states and transient states so that they can $e used to restore the activity/s states later. his saved states will $e assed via -undle in on0reate'( function to restore its states once android recreates a killed activity. 28: this will haen in case of low memory or configuration changes like rotating the hone. on&ave"nstance&tate'(: his function will $e called $y aAndroidAndroidndroid $efore omause or after onause if aAndroidAndroidndroid is forcefully killing your activity. "n this function we have to save all your activity states.
on;estore"nstance&tate'(: his function will $e called after on&tart.
422. When an activity is 0eing started with an intent action >&EFA+;IO3 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 %anifest file. &or example, in an app, I am using the Local-roadcastManager as part of a dispatcher pattern implementation. I would register a 'roadcasteceiver implementation this way (ntentilter ;lter 5 new (ntentilterBF ;lter.addActionB6com.e%ample.android.M@9AC&(>/6F 2ocal#roadcastManaer .et(nstanceBconte%t.reister'eceiverBreceiver, ;lterF
hen when I run the following code, my receiver will receive the locally broadcasted Intent (ntent intent 5 new (ntentBF intent.setActionB6com.e%ample.android.M@9AC&(>/6F 2ocal#roadcastManaer .et(nstanceBconte%t.send#roadcastBintentF
42!. 7ow to get contact num0er "rom contacts content provider >>irst get the all $asic details from $asic ta$le of contacts 0ursor c1 this.get0ontent;esolver'(.3uery' 0ontacts0ontract.0ontacts.04*2*B!;"# null# null# null# null(5 c1.moveo*ext'(5 >>move to first row &tring id c1.get&tring'c1.get0olumn"ndex'0ontacts.B"D((5 >>get its id >>now $ased on that id# you can retrive hone details from other ta$le. 0ursor cur this.get0ontent;esolver'(. 3uery'0ommonDataKinds.,hone.04*2*B!;"# null# 0ommonDataKinds.,hone.04*A0B"D VE %E# new &tringTUWidX# null(5 cur.moveo*ext'(5 &tring num$er cur.get&tring'cur.get0olumn"ndex' 0ommonDataKinds.,hone.*!M-2;((5
42#. 7ow to take an image "rom gallery and i" no images availa0le in gallery I should 0e a0le to take picture "rom camera and return that picture to my activity private static ;nal int *=2=C&9)(C&<'= 5 F 88 ... (ntent pic!(ntent 5 new (ntentBF pic!(ntent.set&ypeB6imae8T6F pic!(ntent.setActionB(ntent.AC&(>/9-=&9C>/&=/&F (ntent ta!e)hoto(ntent 5 new (ntentBMedia*tore.AC&(>/9(MA-=9CA)&<'=F *trin pic!&itle 5 6*elect or ta!e a new )icture6F 88 >r et rom strins.%ml (ntent chooser(ntent 5 (ntent.createChooserBpic!(ntent, pic!&itleF chooser(ntent.put=%tra B
(ntent.=U&'A9(/(&(A29(/&=/&*, new (ntentW G ta!e)hoto(ntent H F startActivityor'esultBchooser(ntent, *=2=C&9)(C&<'=F
42'. What is the di""erence 0etween linear layout and relative layout linear layout + arranges child element in either vertical or horiPontal fashion. ;elative layout + arranges child elements in relative to each other. " mortant roerties of ;elative Layout: 1. android:$elow 9. android:a$ove F. android:to;ightof . android:toLeftof
42. 7ow many kinds o" linear layouts are there 7oriPontal and vertical
42*. What is >dp? GorH >dip? means p ,ixels + corresonds to actual ixels on the screen. in "nches + $ased on the hysical siPe of the screen. 1 "nch 9.@ centimeters mm Millimeters + $ased on the hysical siPe of the screen. pt ,oints + 1>O9 of an inch $ased on the hysical siPe of the screen. $p$ip Density+indeendent ,ixels + an a$stract unit that is $ased on the hysical density of the screen. hese units are relative to a 1
42,. What is importance o" gravity attri0ute in the views android:gravity sets the gravity of the content of the 6iew its used on. android:layoutBgravity sets the gravity of the 6iew or Layout in its arent.
42/. What is adapter What is adapter design pattern $ridge $etween source and adater views
4!5. What is adapterview 7ow many adapter views are availa0le in android any view that takes inut from adater is called as adater view. eg:listview# gallery# sinner# gridview# etc..
4!4. +an you tell me some list adapters Array adater#$ase adater cursor adater#exadale list adater
4!2. +an I give cursor to an array adapter *o $ecause array adater takes + lists 'arraylists(5 cursor adater takes + cursor which is returned from data$ase ta$les uon 3uerying.
4!!. What is custom adapter3 when should I use it. what are the mandatory "unctions I need to implement in custom adapter get6iew# get"tem# get"tem"d# and get0ount are the mandatory functions that have to $e imlemented in 0ustom Adater.
4!#. What is the class that I need to etend to create my own adapter
o create a own custom adater# one can extend -aseAdater# or can extend any of the existing concrete adaters like ArrayAdater# &imle0ursorAdater etc.. *ote: we can also extend or imlement other adater interfaces# $ut it is not so useful. 8enerally extending -aseAdater is enough to create our own custom adater.
4!'. What is the android compilation and eecution process cycle )ava file ++ will $e given to ++ )ava comiler ++ to generate ++ .class file. all .class files ++ will $e given to ++ dx tool ++ to generate single ++ dex file dex file ++ will $e given to ++ dvm ++ to generate ++ final machine code. final machine code ++ will $e given to ++ 0,! ++ to execute.
4!. What is ad0 What is the command to install one application using ad0 command prompt
4!*. What is the de0ugging procedures availa0le in android
4!,. 7ow will you analy@e a crash3 how will "i using logcat after crash logcat will contain file name#excetion name along with line num$er where it has crashed.
4!/. What is a 0reak point and how to watch varia0les while de0ugging $reak oint $reaks the execution. o see value either you can ut cursor on it or right click on varia$les and add to watch
4#5. What is ddms What are the various components in ddms Android rovides a de$ugging tool called the Dalvik De$ug Monitor &erver 'DDM&(.
i) DDM& rovides ort+forwarding services. ii) &creen cature on the device. iii) hread and hea information on the device. iv) Logcat. v) ,rocess. vi) ;adio state information. vii) "ncoming call and &M& soofing# location data soofing# and more.
4#4. What is the di""erence 0etween started service and 0inded service 6tarted service J is used to do some long running oeration in the $ack ground. it will $e alive in memory even if the erson who started it is no longer in memory. either it itself can sto or some other also can sto it. generally services will not have !". it is used to some $ack ground functionalities like sending &M downloading files# etc.. inded service+ is like a client server architecture where clients can re3uest to $inded service to execute some function and return the result. started services will not return results generally. since data flow haens from service to client# there should $e communication channel in the case of $inded services. 4#2. 7ow to achieve 0ind service using IK+ 1. create a service G imlement on0reate'(# on-ind'(# on!n$ind'(# onDestroy'( 9. create .aidl file with interface functions. F. imlement auto generated -inder stu$ class in service. . return o$)ect to this stu$ class from on-ind'(
4#!. 7ow will I know i" a client is connected to a service or not 4##. I want to access a "unctionality "rom one application to other
application3 then should I use content provider or startservice or 0ind service 4#'. I want to access data o" another application in my application3 now do I need to implement content providers in my application or other application has to implement it other alicationwhich is sharing data has to imlement it.
4#. What is the di""erence 0etween local varia0les3 instance varia0les3 and class varia0les Local Variables:
is *eclared Inside a %ethod. %ust be Initiali+ed before use. It won$t compile if not Initiali+ed.
• • •
Instance Variables:
is *eclared Inside a lass. Initiali+ation is not compulsory. ontains *efault -alue. (&or int its , for float its .f, etc.) ompiles even if not Initiali+ed
• • • •
class variables &he class variables must have the !eyword static as the modi;er and are declared inside a class body butoutside o any method bodies. >nly one copy o class variables are created rom the point the class is loaded into the JVM until the the class is unloaded, reardless o the number o object instances that are created rom that class. ( one object instance o that class chanes the value o a class variable then all the other instances see thesame chaned value.
4#*. What is anonymous class Where to use it Anonymous classes are those for which there is no class name# $ut $ody will exist. =ou can create anonymous classes $y extending a $ase class or $y imlementing an interface. 2g: for anonymous class is $utton click listeners in Android.
4#,. What is singleton class3 where to use it show with one eample how to use it "t is a design attern# where a class is designed in such a way that# there is only o$)ect for that class. his can $e achieved in many ways# general way of imlementation is $y making the constructor as rivate# and creating and returning o$)ect through a static method of that class.
4#/. I" I want to listen to my phone locations3 what all the things I need to use Is it 0etter to use network providers or gps providers gs
4'5. &y phone dont have network signal and satellite signal3 now is there any way to "etch my last location where signal was availa0le &tring location,rovider LocationManager.*24;KB,;46"D2;5 >> 4r use LocationManager.8,&B,;46"D2;
Location lastKnownLocation locationManager.getLastKnownLocation'location,rovider(5 his should give your last known location. !se 8,&B,;46"D2; for $etter results.
4'4. I have some data availa0le in docs.google server3 and I want to display it in ta0ular "ashion3 tell me the seuence o" steps to achieve this 4'2. I" I want to start some heavy weight "unctionalities that takes lot o" 0attery power like starting animation or starting camera3 should I do it in oncreate() or onstart() or onresume() o" my activity And where should I disa0le it I" I want to start some heavy weight "unctionalities that takes lot o" 0attery power like starting animation or starting camera3 should I do it in oncreate() or onstart() or onresume() o" my activity And where should I disa0le it &ince heavy weight functions take too much of $attery ower# $etter do it )ust $efore your activity is ready to take user events. so do it in on;esume'(.&ince heavy weight functions take too much of $attery ower# $etter do it )ust $efore your activity is ready to take user events. so do it in on;esume'(. 4'!. Why you should not do heavy "unctionality in onresume and onpause() o" your activity 4'#. What things I can do in onrestart() o" my activity on;estart '( 1.0alled after on&to'( when the current activity is $eing re+dislayed to the user 9."t will $e followed $y on&tart'( and then on;esume'( F."f you have deactivated any cursor in on&to'(# call managedRuery'( again. .Derived classes must call through to the suer class/s imlementation of this method. "f they do not# an excetion will $e thrown.
4''. What is the li"e cycle o" a service
he system calls this method when another comonent# such as an activity# on&tart0omman
re3uests that the service $e started# $y calling startService(). "f you imlement
d'(
this method# it is your resonsi$ility to sto the service when its work is done# $y calling stopSelf() or stopService() methods. he system calls this method when another comonent wants to $ind with the service $y calling bindService(). "f you imlement this method# you must
on-ind'(
rovide an interface that clients use to communicate with the service# $y returning an IBinder o$)ect. =ou must always imlement this method# $ut if you don/t want to allow $inding# then you should return null.
on!n$ind'(
he system calls this method when all clients have disconnected from a articular interface u$lished $y the service. he system calls this method when new clients have connected to the service#
on;e$ind'(
after it had reviously $een notified that all had disconnected in its onUnbind(Intent). he system calls this method when the service is first created
on0reate'(
usingonStartCommand() or onBind(). his call is re3uired to erform one+ time set+u. he system calls this method when the service is no longer used and is $eing
onDestroy'(
destroyed. =our service should imlement this to clean u any resources such as threads# registered listeners# receivers# etc.
4'. What is the li"e cycle o" a 0roadcast receiver there is only one function in $road cast receiver# that is on;eceive'(. -roadcast receiver/s life will start $efore calling on;eceive'( method# and once control comes out of on;eceive'( method# then it will $e killed.
4'*. What is the li"e cycle o" a content provider 0ontent ,roviders don/t have a articular lifecycle# there is not much you can do to control it. he framework manages the creation and destruction of a 0ontent ,rovider'rocess(. hen external clients or comonents outside of the rocess make a re3uest to the 0ontent ,rovider# that re3uest is rocessed in a thread from a thread ool of th e rocess the rovider resides in. And when there are no more re3uests the rocess can $e reclaimed if there are no more active comonents 'activity# service( in that rocess. -ut that is a decision Android takes.
4',. What is the li"e cycle o" a thread
1( *ew he thread is in new state if you create an instance of hread class $ut $efore the invocation of start'( method.
2) =unna0le he thread is in runna$le state after invocation of start'( method# $ut the thread scheduler has not selected it to $e the running thread. F( ;unning he thread is in running state if the thread scheduler has selected it. ( *on+;unna$le '-locked( his is the state when the thread is still alive# $ut is currently not eligi$le to r un. @( erminated
4'/. What is the li"e cycle o" your application process 'alication(,rocess will $e loaded into memory $efore loading first comonent of the alication# and will $e killed after destroying all comonents.-ut if user is visiting that alication very fre3uently# then android might not kill the rocess at all to otimiPe the loading time of that alication. "f user is visiting an alication very fre3uently# then its $etter to retain that alication in the memory rather than killing it. ;eason for this is# next time when user visits the same alication no need to load that alication into memory# as it is already in memory. &o user will feel hay for showing alication very 3uickly. his is called as emty rocess'alication(.
45. 7ow to kill one activity Activity can $e killed rogramatically in two ways. finish'( or finishActivity'int re3uestcode(. finish'( + can $e used $y an activity to kill itself. finishActivity'int re3uestcode( + orce finish another activity that you had reviously started with startActivityor;esult'"ntent intent# int re3uestcode(5 his function will let the arent activity to kill the child activity# which it has started reviously.
44. What is log.d where to use log "unctions Log messages are used to de$ug the rogram. Log.d'( is de$ug log. other functions are Log.i'( + informative Log.e'( + error log Log.w'( + warning log Log.v'( + ver$ose log
42. $raw the li"e cycle o" an activity in case o" con"iguration change 1 on,ause'( +N on&ave"nstance&tate'( +N on0reate'( +N on&tart'( +N on;estore"nstance&tate'( +N on;esume'( 9 on,ause'( +N on&ave"nstance&tate'( +N on&to'( +N onDestroy'(+Non0reate'( +N on&tart'( +N on;estore"nstance&tate'( +N on;esume'( F.on,ause'( +N on&ave"nstance&tate'( +N on&to'( +N on0reate'( +N on&tart'( +N on;estore"nstance&tate'( +N on;esume'( 0onfiguration change : is either orientation change'hone rotation(# or language settings change. "n case of configuration change# android will forcefully kill your activity and recreates it# unless you are not handling configuration changes on your own rogrammatically. hen android kills your activity due to configuration changes# it makes sure that it will definitely call on,ause'( and on&ave"nstance&tate. -ut there is no guarantee a$out call on&to and onDestroy. -ut android documentation doesn/t say that it will not call on&to and onDestroy. it deends. Life cycle in the case of configuration changes can $e any of the otion 1# or 9# or F# $ased on the situation. some times it might not kill activity at all if rogrammer is handling configuration changes rogrammatically# which is not a standard way to do.
4!. What is the di""erence 0etween viewgroup and layout viewgrou + is invisi$le container# and a$stract class. Layouts are more concrete form of view grous. view grous derive from views# and layouts derive from view grous. 2g of layouts are 1.framelayout# 9.relative layout# F.linear layout# etc..
4#. $raw the key event "low in android Key events will flow like this: Android system +N Activity +N Layout +N 6iew +N rogrammer. irst riority will $e given rogrammer written logic# if rogrammer has written some thing to handle some key events it will $e execute first. rom there $ased on the r eturn statement it will decide to flow $ack that key event to arent or not. eg: if rogrammer choose to $lock some key say K2=04D2BC# then for that key code he can say return true5 which will $lock that event and will $e destroyed in rogrammers function only.
4'. When you "ire an intent to start with A+;IO/=6 8:
4. What are the permissions reuired to o0tain phone locations android.ermission.A002&&B"*2BL40A"4* + use this if you are using 8,& features in your rogramming. else android.ermission.A002&&B04A;&2BL40A"4* + use this if you are fetching locations $ased on career network or $y using ii.
4*. 7ow many levels o" security availa0le in android Android suorts 9 levels of security for alications. one at oerating system level or kernel level. other is using ermissionN tags in a level.
4,. 7ow to achive security to your service programmatically in such a way that your service should not get triggered "rom outside applications "f you don/t want to exose your service to outside as# F ways are there. 1. Don/t give intent+fiiter tag# so that outsiders can/t secify intent action to trigger your service. or 9. !ser exortedEfalseE in service tag# so that outside world cant trigger it. or F. !ser local service manager.
4/. What are the seuence o" tests done to map intent with an intent "ilter hen rogrammer starts a comonent $y using an intent# to trigger aroriate comonent android will erform F tests. 1.action test : the action string of intent should match with at least one action string of intent f ilter. 9.data test : data and data tye of intent should match with that of intent filter. F.category test : all the categories of intent should $e there in intent filter. note: "n case of imlicit intent starting an activity# then default category will $e automatically added to intent. "f there is any comonent in manifest file with an intent filter which asses all the F t ests# then android will trigger that comonent. 2lse not. "f there are multile comonents satisfying that intent# and if it is not a $roadcast receiver# then it will ask user to make a decision.
4*5. $escri0e various "olders in android proLect in eclipse
src en Android versionBsuch as Android . assets res 4*4. What is raw "older in eclipse proLect his is )ust like assets folder# $ut only difference is this folder has to $e accessed via ;.)ava file. you can store any assets like M,F or other files.
4*2. 1nder what thread 0road cast receiver will run Default every comonent of android will run in Main thread '!" thread(. &o $roadcast receiver also runs in main thread $y default.
4*!. I" I want to noti"y something to the user "rom 0roadcast receiver3 should I use dialogs or noti"ications Why /nly 0ctivity$s can create1show dialogs. So use notifications
4*#. +an you create a receiver without registering it in mani"est "ile
e can register receiver dynamically in code. $escription : 2very comonent has to get registered in the manifest file. -ut there is an excetion for this rule# a $road cast receiver can get registered dynamically in code. -ecause there may $e some scenarios where we need handle $road casted messages only when our alication is running. "f we register it in manifest file statically# then even if our a is not running# it may trigger our
$road cast receiver.
4*'. I" I want to 0roadcast A;;-=EFBOW action3 should I use send0roadcast() or sendsticky0roadcast Why e have to use send&ticky-road0ast'( $ecause# logically if $attery went down# then this information has to $e availa$le for alications which may run after some time in f uture.
4*. I" I want to set an alarm to trigger a"ter two days3 how should I implement it assume that I may switch o"" the phone in 0etween. 4**. I want to trigger my 0roadcast receiver as long as my activity is in memory3 else it should not get triggered3 how should I achieve this 4*,. What is sleep mode What will happened to +K1 once screen light goes o"" 4*/. 7ow many kinds o" wake locks are availa0le3 which one to use when 4,5. I" I am using "ull wake lock and user presses screen lights o""3 what will happen 4,4. When phone is in sleep mode3 what are the two components that will keep running even though phone is in sleep mode 4,2. -very day night at 42 o clock I need to post some images to "ace0ook3 in that case I will set repeating alarm "or every day night 42 am. ut to upload images I want to start service3 how should I do this 4,!. When you start an activity "rom a noti"ication3 will it start as new task or old task 4,#. Why android "ollows single threaded ui mode 7ow other threads can manipulate ui views 4,'. What is the purpose o" 6QBiteOpen7elper 4,. What is the procedure to upgrade data0ase a"ter "irst release 4,*. 6how with one eample where memory leak possi0ility in Android 4,,. I" I want to write one application "or 0oth phones and ta0lets3 what should I use in my 1I 4,/. I have a thousands o" items in my array3 and I want to display it in listview3 what is the most optimi@ed way to achieve this 4/5. What is r.Lava "ile What does it contain 4/4. Write one application which will get triggered immediately a"ter 0ooting. 4/2. What does .apk "ile contains 4/!. 7ow will pass in"ormation "rom one activity to other activity3 lets say pass userid3 city3 and password to net activity and display it. 6earch 7ome Write
4/*. When to use 6tring3 6tringu""er3 9 6tringuilder 4/,. What is 6tring constant pool What is the di""erence 0etween 0elow two statements i. Which is pre"erred way to use ii. 6tring str4 M >hi?N iii. 6tring str2 M new 6tring(>hi?)N 4//. I" I want to share a 6tring 0etween two threads3 and none o" threads are modi"ying my 6tring which class I have to use 255. I" I want to use my 6tring within only one thread which is modi"ying my 6tring3 then which class I have to use 6imilarly i" I want to my string to 0e changed 0y more than one thread then which class I have to use 254. 7ow does 6tring class look like What is "inal class meant "or 7ow will you implement your own 6tring class 252. What is immuta0le o0Lect 7ow is it di""erent "rom immuta0le class 25!. $epict one eample "or immuta0le class in Lava "ramework 25#. 7ow will you write a class in such a way that it should generate immuta0le o0Lects 25'. $oes 6tring class uses character array internally in its implementation 25. What is the di""erence 0etween char 9 +haracter classes Which one is value type and which one is re" type 25*. What is the meaning o" pass 0y re"erence I" I have an integer array and i" I pass that array name to a "unction3 is it pass 0y value or pass 0y re"erence 25,. I want to use array in my program which has to grow dynamically3 in that case should I use Array GorH ArrayBist GorH %ector What is the di""erence 0etween arraylist and vector Which one o" them is not part o" collections "ramework o" A%A 25/. I want to use dynamically growing array shared 0etween two threads3 should I use arraylist or vector 245. I want to store values o" my employees in a data structure using Lava collections "ramework in such a way that I should 0e a0le to read3 write3 modi"y 9 delete them very "astly. Which datastructure should I use arraylist GorH linkedlist GorH hashsets GorH hashmap 244. Write a program in such a way that ;hread4 will print "rom 44555 9 1pvote ;hread2 4' will $ownvote print "rom 45554. +omment ;hread4 6hare should sleep "or 4 second at every 455th location. ;hread2 should interrupt thread4 once thread2 reaches '55. 242. 7ow will you stop a thread3 which is currently running 24!. I" ;hread4 interrputs ;hread23 how ;hread2 should handle it (8enerally how threads should handle interruptions) how will thread2 know that other threads are interrupting it 24#. What is interrupted eception Which "unctions will throw this eception 7ow to handle it 24'. Assume that two threads t43 9 t2 are running simultaneously in single core +K1. 7ow does t2 will reuest O6 that it wants to wait till t4 is "inished 24. I want to implement threads in my program3 should I etend ;hread class or implement =unna0le inter"ace Which one is 0etter3 Lusti"y your answer in terms o" design. 24*. What will happen i" you return "rom run() "unction o" your thread
24,. What is the di""erence 0etween checked 9 unchecked eceptions Which one programmer should handle 24/. arrayIndeOutO"ounds3