- Get link
- Other Apps
Android Interview Questions
Here in this article, I will be sharing some Android Interview questions collections which will help you to crack your interview very easily.
Android - Core
1. What is Android?
Android is an open-source, Linux-based operating system used in mobiles, tablets, televisions, etc.
2. What is Application?
The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
3. What is App components?
App components are the essential building blocks of an Android app. Each component is an entry point through which the system or a user can enter your app. Some components depend on others. There are four different types of app components:-
i. Activities
ii. Services
iii. Broadcast receivers
iv. Content providers
4. What is Context?
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in.
Application Context: This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of an activity.
Activity Context: This context is available in an activity. This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.
5. What is AAPT?
AAPT stands for Android Asset Packaging Tool. This tool is part of the SDK (and build system) and allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets.
6. What is Armv7?
There are 3 CPU architectures in Android.
i. ARMv7 is the most common as it is optimised for battery consumption.
ii. ARM64 is an evolved version of that that supports 64-bit processing for more powerful computing.
iii. ARMx86, is the least used for these three, since it is not battery friendly. It is more powerful than the other two.
7. Why bytecode cannot be run in Android?
Android uses DVM (Dalvik Virtual Machine ) rather using JVM(Java Virtual Machine).
8. Explain the build process in Android?
Step-1. First step involves compiling the resources folder (/res) using the aapt (android asset packaging tool) tool. These are compiled to a single class file called R.java. This is a class that just contains constants.
Step-2. Second step involves the java source code being compiled to .class files by javac, and then the class files are converted to Dalvik bytecode by the “dx” tool, which is included in the sdk ‘tools’. The output is classes.dex.
Step-3. The final step involves the android apkbuilder which takes all the input and builds the apk (android packaging key) file.
9. What is the Android Application Architecture?
Android application architecture has the following components:
i. Services − It will perform background functionalities
ii. Intent − It will perform the inter connection between activities and the data passing mechanism
iii. Resource Externalization − strings and graphics
iv. Notification − light, sound, icon, notification, dialog box and toast
v. Content Providers − It will share the data between applications
Android - Activity
10. Describe activities??
Activities are basically containers or windows to the user interface.
11. Lifecycle of an Activity?
1. onCreate(): This is when the view is first created. This is normally where we create views, get data from bundles etc.
2. onStart(): Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
3. onResume(): Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
4. onPause(): Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed.
5. onStop(): Called when you are no longer visible to the user.
6. onDestroy(): Called when the activity is finishing
7. onRestart(): Called after your activity has been stopped, prior to it being started again
12. What’s the difference between onCreate() and onStart()?
The onCreate() method is called once during the Activity lifecycle, either when the application starts, or when the Activity has been destroyed and then recreated, for example during a configuration change. The onStart() method is called whenever the Activity becomes visible to the user, typically after onCreate() or onRestart().
13. What are the four essential states of an activity?
i. Active – If the Activity is in the foreground.
ii. Paused – If the Activity is in the background and is still visible.
iii. Stopped – If the Activity is not visible, therefore is hidden or concealed by another Activity.
iv. Destroyed – When the Activity process is completed terminated.
14. Enumerate the three key loops when monitoring an activity?
i. Entire lifetime – activity happens between onCreate() and onDestroy()
ii. Visible lifetime – activity happens between onStart() and onStop()
iii. Foreground lifetime – activity happens between onResume() and onPause()
15. Scenario in which only onDestroy is called for an activity without onPause() and onStop()?
If finish() is called in the onCreate() method of an activity, the system will invoke onDestroy() method directly.
16. Why would you do the setContentView() in onCreate() of Activity class?
As onCreate() of an Activity is called only once, this is the point where most initialization should go. It is inefficient to set the content in onResume() or onStart() (which are called multiple times) as the setContentView() is a heavy operation.
17. What is onSavedInstanceState() and onRestoreInstanceState() in activity?
i. onSaveInstanceState() - is a method used to store data before pausing the activity.
ii. onRestoreInstanceState() - When activity is recreated after it was previously destroyed, we can recover the saved state from the Bundle that the system passes to the activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information. But because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.
18. What are the Activity Launch modes in Android?
1. Standard
2. SingleTop
3. SingleTask
4. SingleInstance
In the AndroidManifest you can use “launchMode” attribute inside the <activity> element to declare the activity’s launch mode like-
<activity android:launchMode = [“standard” | “singleTop” | “singleTask” | “singleInstance”] ../>
1. standard:- This is the default launch mode of an activity (If not specified). It creates a new instance of an activity in the task from which it was started. Multiple instances of the activity can be created and multiple instances can be added to the same or different tasks. In other words you can create the same activity multiple times in the same task as well as in different tasks.
<activity android:launchMode=”standard” />
Example: Suppose you have A, B, C and D activities and your activity B has “launch mode = standard”. Now you again launching activity B – State of Activity Stack before launch B A -> B -> C -> D State of Activity Stack after launch B A -> B -> C -> D -> B
2. singleTop:- In this launch mode if an instance of activity already exists at the top of the current task, a new instance will not be created and Android system will route the intent information through onNewIntent(). If an instance is not present on top of task then new instance will be created. Using this launch mode you can create multiple instance of the same activity in the same task or in different tasks only if the same instance does not already exist at the top of stack.
<activity android:launchMode=”singleTop” />
Example:
Case 1: Suppose you have A, B and C activities and your activity D has “launch mode = singleTop”. Now you launching activity D - State of Activity Stack before launch D A -> B -> C State of Activity Stack after launch D activity A -> B -> C -> D (Here D launch as usual)
Case 2: Suppose you have A, B, C and D activities and your activity D has “launch mode = singleTop”. Now you again launching activity D - State of Activity Stack before launch D A -> B -> C -> D State of Activity Stack after launch D activity A -> B -> C -> D (Here old instance gets called and intent data route through onNewIntent() callback)
3. singleTask:- In this launch mode a new task will always be created and a new instance will be pushed to the task as the root one. If an instance of activity exists on the separate task, a new instance will not be created and Android system routes the intent information through onNewIntent() method. At a time only one instance of activity will exist.
<activity android:launchMode=”singleTask” />
Example:
Case 1: Suppose you have A, B and C activities and your activity D has “launch mode = singleTask”. Now you launching activity D - State of Activity Stack before launch D A -> B -> C State of Activity Stack after launch D activity A -> B -> C -> D (Here D launch as usual)
Case 2: Suppose you have A, B, C and D activities and your activity B has “launch mode = singleTask”. Now you again launching activity B- State of Activity Stack before launch D A -> B -> C -> D State of Activity Stack after launch B activity A -> B (Here old instance gets called and intent data route through onNewIntent() callback) Also notice that C and D activities get destroyed here.
4. singleInstance:- This is very special launch mode and only used in the applications that has only one activity. It is similar to singleTask except that no other activities will be created in the same task. Any other activity started from here will create in a new task.
<activity android:launchMode=”singleInstance” />
Example:
Case 1: Suppose you have A, B and C activities and your activity D has “launch mode = singleInstance”. Now you launching activity D - State of Activity Stack before launch D A -> B -> C State of Activity Stack after launch D activity Task1 — A -> B -> C Task2 — D (here D will be in different task) Now if you continue this and start E and D then Stack will look like- Task1 — A -> B -> C -> E Task2 — D
Case 2: Suppose you have A, B, C activities in one task and activity D is in another task with “launch mode = singleInstance”. Now you again launching activity D- State of Activity Stack before launch D Task1 — A -> B -> C Task2 — D State of Activity Stack after launch B activity Task1 — A -> B -> C Task2 — D (Here old instance gets called and intent data route through onNewIntent() callback)
19. How does the activity respond when the user rotates the screen?
When the screen is rotated, the current instance of activity is destroyed a new instance of the Activity is created in the new orientation. The onRestart() method is invoked first when a screen is rotated. The other lifecycle methods get invoked in the similar flow as they were when the activity was first created.
20. What is the relationship between the lifecycle of an AsyncTask and the lifecycle of an Activity? What problems can this result in, and how can these problems be avoided?
An AsyncTask is not tied to the lifecycle of the Activity that contains it. If the Activity is destroyed and a new instance of the Activity is created, the AsyncTask won’t be destroyed. This can lead to a number of problems, but the major ones an Android developer should be aware of are: Once the AsyncTask completes, it’ll try to update the former instance of the Activity, resulting in an IllegalArgumentException. Since the AsyncTask maintains a reference to the previous instance of the Activity, that Activity won’t be garbage collected, resulting in a memory leak. The solution is to avoid using AsyncTasks for long-running background tasks.
21. How to prevent the data from reloading and resetting when the screen is rotated?
The most basic approach would be to use a combination of ViewModels and onSaveInstanceState().
22. Mention two ways to clear the back stack of Activities when a new Activity is called using intent?
The first approach is to use a FLAG_ACTIVITY_CLEAR_TOP flag. The second way is by using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK in conjunction.
23. How would you update the UI of an activity from a background service?
We need to register a LocalBroadcastReceiver in the activity. And send a broadcast with the data using intents from the background service. As long as the activity is in the foreground, the UI will be updated from the background. Ensure to unregister the broadcast receiver in the onStop() method of the activity to avoid memory leaks. We can also register a Handler and pass data using Handlers.
Android - Fragment
24. What is a Fragment?
A Fragment represents a behavior or a portion of user interface in a Fragment Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
25. Lifecycle of a Fragment?
The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:-
1. onAttach(Activity) called once the fragment is associated with its activity.
2. onCreate(Bundle) called to do initial creation of the fragment.
3. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
4. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity onCreate.
5. onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
6. onStart() makes the fragment visible to the user (based on its containing activity being started).
7. onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed). As a fragment is no longer being used, it goes through a reverse series of callbacks:
8. onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
9. onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
10. onDestroyView() allows the fragment to clean up resources associated with its View.
11. onDestroy() called to do final cleanup of the fragment's state.
12. onDetach() called immediately prior to the fragment no longer being associated with its activity.
26. What is the difference between fragments & activities? Explain the relationship between the two.
An Activity is an application component that provides a screen, with which users can interact in order to do something whereas a Fragment represents a behavior or a portion of user interface in an Activity (with its own lifecycle and input events, and which can be added or removed at will).
27. When should you use a fragment rather than an activity?
i) When there are UI components that are going to be used across multiple activities.
ii) When there are multiple views that can be displayed side by side (viewPager tabs)
iii) When you have data that needs to be persisted across Activity restarts (such as retained fragments)
28. Difference between adding/replacing fragment in backstack?
i) Replace:- replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked.
ii) Add:- add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in ‘paused’ state hence when a back button is pressed onCreateView is not called for the existing fragment(the fragment which was there before new fragment was added). In terms of fragment’s life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add.
29. Difference between Activity and Fragment Activity?
A FragmentActivity is a subclass of Activity that was built for the Android Support Package. The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.
30. You’re replacing one Fragment with another — how do you ensure that the user can return to the previous Fragment, by pressing the Back button?
We need to save each Fragment transaction to the backstack, by calling addToBackStack() before you commit() that transaction
31. Callbacks invoked during addition of a fragment to back stack and while popping back from back stack?
addOnBackStackChangedListener is called when fragment is added or removed from the backstack.
32. What is Headless Fragment?
A headless Fragment is simply a Fragment that does not have a layout or View to render. Fragments are also context and life-cycle aware and with setRetainInstance() set to true, they are not destroyed and recreated on orientation changes.
33. What are retained fragments?
By default, Fragments are destroyed and recreated along with their parent Activity’s when a configuration change occurs. Calling setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle, signaling the system to retain the current instance of the fragment when the activity is recreated.
34. What is the difference between Dialog & DialogFragment?
A fragment that displays a dialog window, floating on top of its activity’s window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment’s state. Dialogs are entirely dependent on Activities. If the screen is rotated, the dialog is dismissed. Dialog fragments take care of orientation, configuration changes as well.
35. Difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?
i) FragmentPagerAdapter:- the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).
ii) FragmentStatePagerAdapter:- the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.
- Get link
- Other Apps
Comments
Post a Comment