Saturday, January 3, 2015

250 Android Interview Questions - part 1

I am giving set of 250 Android interview questions here, which I have answered in android interview questions and answers - skillgun
                                            
Android Interview Questions:
1.       Draw architecture diagram of android framework.
2.       Which kernel(Operating system) is used in android?
3.       In which language android framework is written?
4.       What does DVM stand for ?
5.       Why DVM why not JVM?
6.       Which layer does DVM sits?
7.       What is the latest version of android? Can you tell me what is the new concepts added in this version?
8.       Explain life cycle of activity?
9.       If I have a broadcast receiver that updates my UI frequently, then where should I register that broadcast receiver in my activity life cycle functions?
10.   Can I save all my databse tables updations in onStop() of activity? If not explain why and also explain where should I save db tables?
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?
12.   What will happen if I remove super.oncreate() from oncreate() function of activity?
13.   What is the purpose f super.oncreate() ?
14.   Show me how does intent-filter of main activity looks like? What is the action and what is the category?
15.   What is the importance of version code and version name attributes in manifest file?
16.   Can one application have more than on manifest file?
17.   Can I create activity without xml file?
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?
19.   Give me two examples of configuration changes in phone?
20.   What is the mandatory life cycle function that will get called in case of configuration changes?
21.   Can I save large images downloaded from internet in onsaveinstancestate() ?
22.   What is the difference between this & getapplicationcontext() ? which one to use when?
23.   Every application will have by default one thread? True or false?
24.   What is ANR (application not responding)? What is the reason for this problem and what is the solution for that problem?
25.   Main thread will have a looper , true or false?
26.   By default a given process will have how many threads? Who will create those threads?
27.   What will happen if I remove oncreate() & onstart() from activity? Will it run?
28.   Can I have an activity without UI?
29.   What is the difference between intent, sticky intent, pending intent?
30.   What is the difference between implicit intent and explicit intent, give one example?
31.   How many components are there in an intent?
32.   Can I give more than one action in a given intent?
33.   Can I give more than one category in a given intent?
34.   Create an intent to start calling a number “12345” ?
35.   what is the importance of putextras in intent? How is it different from setdata() ? any way both are passing data only , so in that case what is the difference?
36.   What is the difference between thread and service?
37.   Can I have a service without thread?
38.   If I want to touch ui from another thread can I touch directly? What will happen if I do so?
39.   How to achieve inter thread communication?
40.   What is the difference between thread and handler thread?
41.   what will happen if I bind a service from a broad cast receiver, is there any problem?
42.   Can I start a service from a broadcast receiver?
43.   How to start a service with foreground priority?
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?
45.   If I start an activity with implicit intent, and there is no matching intent-filter then what will happen?
46.   If I send a broad cast with implicit intent, and there is no matching intent-filter then what will happen?
47.   Write a broadcast receiver that gets triggered once phone boot is done?
48.   What will happen if I don’t pass any action in an implicit intent, will it trigger any component?
49.   Can I start a content provider using an intent?
50.   I have one intent filter without any action, then can I trigger this component from outside of this application?
51.   Can I have more than one action in my intent-filter?
52.   Can I have more than one category in my intent-filter?
53.   Can I have extras in my intent-filter?
54.   I want to start something in the background in my activity, should I use thread or should I start service? Why?
55.   If I crate a thread in my activity and if I stop my activity what will happen to that thread, will it be alive or dead?
56.   If I start a service from my activity and if I stop my activity what will happen to that service, will it be alive or dead?
57.   How many ways are there to kill a service?
58.   If I want my service to allow binding, then what is the function that I need to implement in my service class?
59.   Can I create a customized textview?
60.   How many ways you can store persistent data?
61.   What is the use of content provider? Will it support shared preferences?
62.   If I want to share some data with outside applications then what is the component in android to use?
63.   Can one application access other app database directly?
64.   Where does the database get stored?
65.   What is the extension of your shared preference file? Where is it stored?
66.   What is the default shared preference file name of an activity?
67.   What is the difference between task, process, application, and thread?
68.   Does android support multi tasking? If yes explain how to start a new task when you are already running one task?
69.   Does android support multi threading?
70.   What is the mechanism used by android for Inter-process-communication?
71.   How binder is different from serialization?
72.   How serialization differ from parcel?
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?
74.   What is looper, message queue, and a Handler? Where do you need these components?
75.   Can I send a message from thread-a to thread-b, if thread-b didn’t prepare its looper?
76.   How to avoid synchronization problems in threads?
77.   What is the difference between synchronized block(statement) and synchronized methods?
78.   If I want to create a service with one worker thread how to achieve it?
79.   How to create multi threaded service?
80.   How to create a service with threads and that updates ui?
81.   What will happen if you start a service that does heavy functionality without starting a thread?
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?)
83.   What is the time limit of a broadcast receiver, what will happen if it crosses that time limit?
84.   What is the difference between sendbroadcast(), sendorderedbroadcast(), sendstickybroadcast() ?
85.   If I want to start an activity that gives a response, what is the function I need to use to start that activity?
86.   If I startactivityforresult() and the child activity gets crashed what is the result code obtained by the parent?
87.   In case of low memory if android closes a service forcefully, then will it restart automatically or user has to start it?
88.   What are the various return values of onstartcommand() , and when to use what?
89.   Let’s 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?
90.   What is empty process and what is its priority? When android will use this concept?
91.   How does android achieves seamlessness. What is the meaning of seamlessness?
92.   What is the difference between menus and dialogs?
93.   How many kinds of menus are there in android?
94.   How many kinds of dialogues are there in android?
95.   I want to design one application where I take username, password and connect to the gmail and show the status of login to the user. Now how to design this application? How many components will be there?
96.   What is the use of httpclient class?
97.   What is the difference between httpget() and httppost() methods, when to use what?
98.   What does httpclient.execute() return?
99.   What  are static variables stored in memory segments?
100.                        If I want to secure my preference file from other activities in my app, then should I use getpreferences() or getsharedpreferences()?

Android Interview Questions - part 6

How to get image from gallery, in android?
Intent in = new Intent();
in.setType("image/*");
in.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(in, 0);

If I want to start some heavy weight functionalities that takes lot of battery power like starting animation or starting camera, should I do it in onCreate() or onStart() or onResume() of my activity? And where should I disable it?
Since heavy weight functions take too much of battery power, better do it just before your activity is ready to take user events. so do it in onResume().

When an activity is in stopped state, is it still in memory or not?
when onStop() is called, then activity is still in memory and all its states and variables are intact.

How to pass data between activities? let’s say pass user id, city, and password to next activity and display it.
Intent in = new Intent();
in.setAction("ACTION"); //this should match with other activity intent-filter
in.putExtra("uid","tech");
in.putExtra("city","Bangalore");
in.putExtra("pw","android");

How to take picture from camera in android?
//make a folder "pics" to store pics taken by the camera using this
final String directory = Environment.getExternalStoragePublicDirectory                                       (Environment.DIRECTORY_PICTURES) + "/pics/";
File nd = new File(directory);
nd.mkdirs();

//what is the picture name?
String file = directory+"myfile"+".jpg";
File myFile = new File(file);
try {
   myFile.createNewFile();
} catch (IOException e) {}       

Uri myUri = Uri.fromFile(myFile);

//prepare intent for starting camera
Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
in.putExtra(MediaStore.EXTRA_OUTPUT, myUri);

startActivityForResult(in, 1);

How to rotate an image in ImageView?
Matrix m=new Matrix();
imageView.setScaleType(ScaleType.MATRIX);  
m.postRotate((float) angle, pivX, pivY);
imageView.setImageMatrix(matrix);

final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
           RotateAnimation.RELATIVE_TO_SELF, 0.5f,
           RotateAnimation.RELATIVE_TO_SELF, 0.5f);


How to get current date in android?
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdate = new SimpleDateFormat("dd-MMM-yyyy");
String date = sdate.format(cal.getTime());

SimpleDateFormat dateFmt = new SimpleDateFormat("yyyyMMdd_HHmmss");
String date = dateFmt.format(new Date());


What is the difference between margin and padding in android?

Which of the following are appropriate for saving the state of an android applications?
Activity.onPause() is the only last guaranteed function to be called in activity life cycle, before killing an activity in all the scenarios.
So save all your persistent data in onPause().

What does the flag FLAG_ACTIVITY_NEW_TASK do here?
Intent in = new Intent();
in.setAction("com.android.myproject.MYACTION");
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);

Description from developer android documentation:
If this flag is set, then this activity will become the start of a new task on this history stack.
When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in.

What does the flag FLAG_ACTIVITY_SINGLE_INSTANCE do here?
Intent in = new Intent();
in.setAction("com.android.myproject.MYACTION");
in.setFlags(Intent.FLAG_ACTIVITY_SINGLE_INSTANCE);
startActivity(in);

This will start a new activity in a new task, where only this activity will be there in that task and no other components. if at all new components are launched from this new activity, they will be launched in a different task.

Android Interview Questions - part 5

Is it mandatory to implement oncreate() & onstart() of activity life cycle ? Will it run if those life cycle methods are removed?
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.


Is it possible to have an Activity without UI?
Generally every activity will have UI (User Interface) screens. But if programmer wants he can omit UI and do some background functionality with an Activity.
Note: To do background functionality its better to use service than an activity with out UI. It makes more sense.


Some important points to remember about activity life cycle:
When a dialog comes on top of an existing activity, then existing activity will move to partially invisible state by calling onPause().
When lcd goes off, activity will be moved to onPause() state. This is a special case.


Android ANR(Application Not Responding) : What is the UI response time limit in android. (I.E with in how many seconds main thread has to respond to user actions?)
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).


Activity life cycle: What is the mandatory activity life cycle function that will get called in case of configuration changes?
In case of low memory or configuration changes, android will call both onPause() and onSaveInstanceState() with out fail. Exception: there is one exceptional case, that is if programmer is handling configuration changes, then in that case it will not call those functions.
Activity life cycle onStop: Can I save all my databse table updates in onStop() of activity? If not explain why and also explain where should I save db tables?
In case of low memory or configuration changes, there is a chance that android may force-kill your application before reaching onStop(). onPause() is the only function that will be called with out fail before killing the application. so save all persistent data like DB tables in onPause() only.
Note : We can't save all database tables in onSaveInstanceState, because that function will not be called if user presses back button.


Save image in onsaveinstatncestate: A heavy image downloaded from internet in onCreate() of an activity. Is it possible to save it in onsaveinstancestate() in case of configurationChanges?
Generally configuration changes causes activity to get destroyed and recreated. So if you have downloaded heavy image from internet in onCreate() function, then there is a chance that it will be re downloaded in onCreate() one more time if user rotates the phone. To avoid this we can have a static reference to that image to avoid multiple downloads.


What is the difference between px, dp, dip, and dpi ?
px - is meant for absolute pixels. This is used if you want to give in terms      of absolute pixels for width or height. Not recommended.


dp/ dip - both mean same, density independent pixels. This is alternative of      px. Generally we never use px because it is absolute value. If you use px      to set width or height, and if that application is being downloaded into       different screen sized devices, then that view will not stretch as per the     screen original size. dp is highly recommended to use in place of px.
  Use dp if you want to mention width and height to grow & shrink dynamically    based on screen sizes.
  
  if we give dp/dip, android will automatically calculate the pixel size on      the basis of 160 pixel sized screen.


sp - Scale independent pixels. when mentioning the font sizes to fit for          various screen sizes, use sp. This is similar to dp.Use sp especially for      font sizes to grow & shrink dynamically based on screen sizes.


dpi- dots per inch. It is the resolution factor. More the dpi better and    higher the screen resolution.


Math logic behind it:
1dp = 1px in 160 dpi screen. Means 1 dp is equal to 1physical px of a device having 160 dots per inch.
so no of dynamic pixles for a given dp is = (dp's)*(density/160).
For example on 240dpi screen 1dp = 1.5px (physical pixels)


What is android:gravity attribute in the view tag?
android:gravity property is used to align the view content either right/top/bottom/center/.. with in that view.


what is the life cycle of an activity in case of configuration change or orientation change?
Configuration change : is either orientation change(phone rotation), or language settings change.
In case of configuration change, android will forcefully kill your activity and recreates it, unless you are not handling configuration changes on your own programmatically.


When android kills your activity due to configuration changes, it makes sure that it will definitely call onPause() and onSaveInstanceState. But there is no guarantee about call onStop and onDestroy. But android documentation doesn't say that it will not call onStop and onDestroy. it depends.


Life cycle in the case of configuration changes can be any of the option 1, or 2, or 3, based on the situation. some times it might not kill activity at all if programmer is handling configuration changes programmatically, which is not a standard way to do.


Activity life cycle: Why you should not do heavy functionality in onPause()  of your activity?
onPause() will be called as the first indication that user is moving away from your activity, that means intentionally user is moving to next screen, so more the time you hold control in onPause() more it will irritate user. so don't hold control here for too much of time.


What is Bundle? What does it contain in onCreate() of your activity?
Bundle is a data holder, which holds data to be passed between activities.
In case of forceful closing of an activity, android will save all its UI states and transient states so that they can be used to restore the activity's states later. This saved states will be passed via Bundle in onCreate() function to restore its states once android recreates a killed activity.
EG: this will happen in case of low memory or configuration changes like rotating the phone.


onSaveInstanceState():
This function will be called by aAndroidAndroidndroid before “ompause” or after “onpause” if aAndroidAndroidndroid is forcefully killing your activity. In this function we have to save all your activity states.


onRestoreInstanceState():

This function will be called after “onStart”.

Own a smart phone with exciting offers:

Android Interview Questions - part 4

What is android raw folder in eclipse project?
This is just like assets folder, but only difference is this folder has to be accessed via R.java file. you can store any assets like MP3 or other files.

What is the maximum memory limit given for each process or application in android?
16 MB is the maximum memory limit given to any given android application. Some second generation phones will return 24 MB of memory for each process or even more.

How to send an SMS in android, through code ?
Eg: If I want to send a message to destination number "9741200300", then what is the correct code to do it?
SmsManager s = SmsManager.getDefault();
       s.sendTextMessage("9741200300", null,
                       "Hi how are you?", null, null);

Note: first parameter is destination number, second parameter is source number which you can omit, third parameter is text to be sent, fourth parameter is sent intent, fifth parameter delivery intent.

Sent intent: You can give a pending intent that should be broad casted once your message reaches your service providers SMS center.
Delivery intent: you can give a pending intent that should be broad casted once your message is delivered to the destination phone.

What is rooting?
It is the process of allowing users of smartphones, and other android enabled devices to get the privileged permissions (root access).
rooting allows to run any appliction that requires admin level permissions in the android system And can perform any operation which is not allowed by normal android user.
rooting is also done to overcome the limitations set by carriers and OEM (original equipment manufacturers) on a phone. Rooted phone can be used any where with any carrier network.

What is the difference between permission and uses-permission in android?

i. permission tag is used to enforce a user defined permission on a component of your application.
ii. uses-permission tag is used to take a permission from the user for your application.
iii. permission tag is used when you want other applications to seek permission from the user to use some of your applications components.

How to send an email in android through code? What is the correct intent to send an email?
       Intent in = new Intent(Intent.ACTION_SEND);  
       in.setType("message/rfc822"); //this is MIME type of email
       in.putExtra(Intent.EXTRA_EMAIL, new String[]{"user@gmail.com",
                       "more@gmail.com"}); // to address field
       in.putExtra(Intent.EXTRA_SUBJECT, "Hey imp!"); //subject of your mail
       in.putExtra(Intent.EXTRA_TEXT, "WHAT ARE YOU DOING?"); //body of your email
       
       startActivity(Intent.createChooser(in, "Select one option"));


What is the difference between this context and getapplicationcontext ?
There are two types of contexts available in android to create any component.
1. this context (or) this pointer
2. application context

When programmer wants to create any component or control, then you have to use one of the contexts.
eg: TextView t = new TextView(this);
Here we are using this pointer (context).
eg: static TextView st = new TextView(getApplicationContext());
Here we are using application context, because it is a static variable whose life time will be through out application life time.
If you use this pointer here, then it will leak memory (memory wastage) of your activity.

When to use this & getapplicationcontext:
1.If the control or variable you are creating should belong to application level then use applicationContext.
2.If the control or variable you are creating should belong to Activity level then use this pointer or this context.

Note: Generally people will think that java will not have memory leaks. But if you don't use contexts properly, then it might lead to some dangerous memory leaks in your android application.
Tip : Don't ever link between this pointer and static variables. If you follow this simple tip, you can almost reduce most of your memory leaks in your program.

what is the permission required to make a call in android, by using  ACTION_CALL ?
To make calls, we should have below permission tag in manifest file after </application> tag.
<uses-permission android:name = "android.permission.CALL_PHONE"/>.

how to create customized textview in android?

TextView is a predefined UI control given by android. If you don't like or wanted to enhance its properties, then you can create your own class by extending TextView class and implementing your own functionalities.

Android Interview Questions - part 3

What is the difference between DVM and JVM? Why Android opted for DVM?
Android team preferred DVM over JVM because of below given reasons.
1. Though JVM is free it was under GPU license, which is not good for Android as most of the Android is under Apache license.
2. JVM was designed by keep desktops in mind. So it is too heavy for embedded devices.
3. DVM takes less memory, runs & loads faster compared to JVM.
4. Since mobile devices have lot of limitations like low CPU speed and less Memory, it is always better not to use heavy components like JVM.

Which layer does Dalvik Virtual Machine sit?
Every android application runs in DVM. To run an application it requires memory, process, threads and other resources. But all these resources are under control of kernel. So DVM has to interact with driver layer for memory and thread management, it sits just above driver layer (that is.. it sits in library layer)

What is the importance of version code and version name attributes in manifest file?
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.

Give two examples for configuration changes in Android?
configuration changes include: rotating the phone, having virtual keypad on, and changing language settings in settings.

What is the difference between implicit intent and explicit intent, give one example?
Implicit intent - Intent with out target component name; Explicit intent - Intent with target component name.

How to make a phone call from an android application?
Intent in = new Intent();  
in.setAction(Intent.ACTION_CALL);
in.setData(Uri.parse("tel:12345"));
startActivity(in);

What is the difference between intent, sticky intent, and pending intent?
intent - is a message passing mechanism between components of android, except for Content Provider. You can use intent to start any component.
Sticky Intent - Sticks with android, for future broad cast listeners. For example if BATTERY_LOW event occurs then that intent will be stick with android so that if any future user requested for BATTER_LOW, it will be fired;
Pending Intent - If you want some one to perform any Intent operation at future point of time on behalf of you, then we will use Pending Intent. Eg: Booking a ticket at late night when your application is not running. In this scenario we will create a pending intent to start a service which can book tickets at late night and hand it over to Alarm Manager to fire it at that time.
What type of kernel is used in Android?
Linux modified kernel (Monolithic) is used in Android.

What is r.java in android? What does it contain?
all resources located in res folder are mostly .xml files, which will not be understood by java compiler. So aapt (android application packaging) tool will convert all those xml files and other resources into a java file, which has identification numbers(pointers) to all those resources. if we want to access any resource from the code, then we can access through this R.java file. full form is Resource.java file.

What is APK in android, and What does .apk  file contains?
APK - Application Package file. It is a file format used to distribute and install android applications.

.apk will contain single .dex file, zipped resources, other non java library files (c/c++). .dex file will internally contains converted .class files. other wise .apk will not contains .class files.