Android Experienced Questions

1. What is the difference between Serializable and Parcelable? Which is the best approach in Android?

Serializable : is a Java interface that enables an object to be serialized, When an object is serialized, it is converted into a byte stream that is easily readable by the receiving end. The receiving end can then convert the byte stream back into an object. Serialization is a quick and efficient way of transferring data across activities.

Parcelable is an Android-specific interface that enables an object to be passed as a parameter from one activity to another. This is a more efficient method compared to serialization, as it doesn’t require the object to be converted into a byte stream. When an object is passed using parcelable, it is passed directly from one activity to another. Parcelable also has the advantage of being able to pass a large amount of data in a single call, making it more efficient than serialization.

2. What is SSL Pinning?

SSL pinning in Android is a security measure that helps protect against man-in-the-middle attacks by ensuring that your app only communicates with trusted servers. It involves associating a specific SSL/TLS certificate with a particular server and then validating that certificate within your Android app.

in short

SSL Pinning:

  • SSL pinning involves embedding a specific SSL certificate (or its public key) within your Android app.

3. What is AIDL?

AIDL(Android Interface Definition Language) is a tool that handles the interface requirements between a client and a service for interprocess communication(IPC) to communicate at the same level.

The process involves dividing an object into primitives that are understood by the Android operating system. Data Types supported by AIDL is as follows:

  • String

  • List

  • Map

  • CharSequence

  • Java data types (int, long, char, and boolean)

4. What is Memory Leak?

Memory leaks happen when an Android app doesn't free up memory properly, leading to performance issues and potential crashes. To prevent leaks, release resources when they are no longer needed and use tools like memory profilers to identify and fix issues.

Why it happens:

- Unreleased Objects: When objects (like activities, fragments, or views) are not properly released or destroyed after they are no longer needed.

Consequences:

- Sluggish Performance: As the app uses more memory, it can become slower and less responsive.

- Crashes: Excessive memory usage can lead to app crashes, especially on devices with limited memory.

How to Prevent:

- Release Resources: Ensure that you release or destroy objects when they are no longer needed. For example, use `onDestroy()` for activities and fragments.

- Use Weak References: Use weak references for objects that should not prevent garbage collection.

Tools to Help:

- Memory Profilers: Android Studio provides tools to help identify and fix memory leaks. Use them to analyze your app's memory usage.

5. ActivityA to ActivityB(lifecycle methods) in android.

In Android development, activities are the building blocks of an app, and they go through various lifecycle stages. Here's a simplified explanation of the lifecycle methods when transitioning from `ActivityA` to `ActivityB`:

1. ActivityA Starts ActivityB:

- `onCreate`: ActivityA's creation code.

- `onStart`: ActivityA becomes visible.

- `onResume`: ActivityA is now in the foreground.

- `onPause`: ActivityA loses focus but is still visible.

2. ActivityB Starts:

- `onCreate`: ActivityB is created.

- `onStart`: ActivityB is visible but not active.

- `onResume`: ActivityB is now in the foreground.

- `onStop`: ActivityA is Stop (not visible but still running).

3. Back Button Pressed or Finish():

- `onPause`: ActivityB is paused.

- `onStop`: ActivityB is no longer visible.

- `onDestroy`: ActivityB is destroyed.

4. Returning to ActivityA:

- `onRestart`: ActivityA is restarted.

- `onStart`: ActivityA becomes visible again.

- `onResume`: ActivityA is in the foreground.

These methods allow you to manage the state of your activities and perform necessary actions at different points in their lifecycle.

6. Share data between activities and fragments.

  • Data Sharing Between Activities:

    • Use Intents: Send data from one activity to another using Intent.putExtra() method.

    • Example: Intent.putExtra("key", data);

  • Data Sharing Between Fragments:

    • Bundle: Pass data between fragments using a Bundle.

Communication Between Activity and Fragment:

  • Use Interfaces: Define an interface in the fragment, implement it in the activity, and communicate through the interface.

7. What is Live data in android.

In Android, "live data" typically refers to an observable data holder class that is part of the Android Architecture Components. It's designed to hold and observe data changes, making it easier to manage and update user interfaces in a reactive manner.

8. What is Paging in android.

Paging in Android refers to a mechanism that helps in efficiently loading and displaying large sets of data, especially when dealing with lists or grids. Instead of loading all the data at once, which can be resource-intensive and lead to performance issues, Paging loads data in smaller, manageable chunks or pages.

9. What is WorkManager in android.

WorkManager is a library in Android that helps you manage background tasks in your app, making it easier to schedule and execute tasks even when the app is not actively running. It provides a simplified API for deferrable and guaranteed execution of tasks, taking into account factors like device battery status and network conditions.

10. What is Room DB.

Room DB in Android is a persistence library provided by Google that makes it easier for developers to work with a SQLite database in their Android apps. It acts as an abstraction layer over SQLite, simplifying database operations and providing compile-time checks for SQL queries.

Key components of Room DB:

  1. Entity: An annotated class that represents a table in the database. Each instance of the class corresponds to a row in the table.

  2. DAO (Data Access Object): An interface or abstract class that defines methods for accessing the database. Developers use annotated methods in the DAO to perform CRUD (Create, Read, Update, Delete) operations.

  3. Database: An abstract class that represents the database itself. It includes a method that returns an instance of the DAO, and it's annotated with information about the entities in the database.

11. Explain different launch modes in Android.

Activity launch modes determine how Android handles the launching of a new instance of an activity when it's already present in the task stack. There are four main launch modes:

  1. Standard: This is the default launch mode. Each time you start the activity, a new instance is created and added to the task stack. This can lead to multiple instances of the same activity in the stack.

  2. SingleTop: In this mode, if a new instance of the activity is requested and the current instance is already at the top of the stack, the current instance will be reused (instead of creating a new one). If not at the top, a new instance will be created.

  3. SingleTask: This mode ensures that only one instance of the activity exists in the entire task stack. If an instance already exists, the system will bring it to the foreground (reusing it) instead of creating a new one.

  4. SingleInstance: Similar to SingleTask, but more isolated. An activity with this launch mode will create a new task, and only that activity will exist in that task. It's rarely used.

Choosing the right launch mode depends on the navigation flow you want to achieve. Standard is often suitable for most cases. SingleTop and SingleTask can be used when you want to control how instances are reused. SingleInstance is quite specialized and usually reserved for specific scenarios.

Remember, launch modes play a crucial role in managing the task and activity stack behavior in your Android app.

  1. Solid principle in Android in easy sentences

Sure, I can help with that! The SOLID principles are guidelines in software design, including Android apps:

  1. Single Responsibility Principle (SRP): Each class should have only one reason to change. It should do one specific thing well.

  2. Open/Closed Principle (OCP): Classes should be open for extension but closed for modification. You can add new features without altering existing code.

  3. Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types without affecting program correctness. In other words, derived classes should be able to replace their base classes without causing issues.

  4. Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use. It's better to have smaller, specific interfaces rather than one large, general-purpose interface.

  5. Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. This promotes flexibility and easier maintenance.

These principles help create more maintainable, flexible, and understandable Android code.

  1. Explain Singleton class

A Singleton class is a design pattern used in software engineering to ensure that a class has only one instance and provides a global point of access to that instance. This pattern is particularly useful when you want to control access to a resource, manage configuration settings, or maintain a single point of control, such as a logging system or a database connection.

In a Singleton class:

  1. There is a private constructor to prevent the direct creation of instances from outside the class.

  2. The class typically has a private static variable that holds the single instance of the class.

  3. A public static method, often named getInstance(), is provided to access the single instance. This method creates the instance if it doesn't exist or returns the existing instance.

Here's a simple example in Java:

java

public class Singleton {

private static Singleton instance;

private Singleton() {

// Private constructor to prevent external instantiation.

}

public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

}

return instance;

}

// Other methods and fields can be added here.

}

Usage:

java

Singleton singleton = Singleton.getInstance();

This ensures that you always work with the same instance of the Singleton class throughout your application, maintaining a single point of control and resource management.

15. What are broadcast receivers? How is it implemented?

  • A broadcast receiver is a mechanism used for listening to system-level events like listening for incoming calls, SMS, etc. by the host application. It is implemented as a subclass of BroadcastReceiver class and each message is broadcasted as an intent object.

    public class MyReceiver extends BroadcastReceiver { public void onReceive(context,intent){} }

16. Explain in detail about the important file and folders used when you create a new Android application.

  • App:

    It describes the basic characteristics of the application and defines each of its components.

    java:

    • This contains the .java source files and .kt(source code written in Kotlin) source files of your project. By default, it includes a MainActivity.java or MainActivity.kt source file.

    • You create all the activities which have .java and .kt extensions under this file and also it includes all the code behind the application.

    res:

    • It is used to store the values for the resources that are used in various Android projects to include features of color, styles, dimensions, etc.

    • It is a directory for files like styles.xml, strings.xml, colors.xml, dimens.xml, etc.

    Scripts:

    This is an auto-generated file that consists of compileSdkVersion, buildToolsVersion, minSdkVersion, targetSdkVersion, applicationId, versionCode, and versionName. For example, build.gradle is a script file placed in the root project directory, defines build configurations that will be applied to all modules in your project.

17. What database is used in Android? How it is different from client-server database management systems?

SQLite is the open-source relational database used in Android. The SQLite engine is serverless, transactional, and also self-contained. Instead of the client-server relationship of most database management systems, the SQLite engine is integrally linked with the application. The library can be called dynamically and it can make use of simple function calls that reduce latency in database access.

18. What are the differences between Service and Thread?

Service :

  • Service is an application component that facilitates an application to run in the background in order to perform long-running operations without user interaction.

  • It exposes few functionalities to other applications by calling Context.bindService().

  • When an application is killed, service is not killed.

Thread

  • A Thread is a concurrent unit of execution.

  • Google has brought in handlers and loopers into threads.

  • When an application is killed, the thread is killed.

19. What is the content provider? How it is implemented?

A content provider in Android is like a data manager that helps different apps securely share and access information. It acts as a bridge, allowing apps to interact with each other's data while maintaining privacy. To implement a content provider, you create a special class that defines how data can be accessed and updated. This ensures a standardized and secure way for apps to share and retrieve information in the Android system.

public class MyContentprovider extends ContentProvider { public void onCreate(){} }

20. What is the significance of the .dex file?

Android programs are compiled into a .dex file (Dalvik Executable file) by DVM, which are then zipped into a .apk file on the device. .dex files are created by translating compiled applications written in java. .dex is a format that is optimized for effective storage and memory-mappable executions.

21. What is the difference between compileSdkVersion and targetSdkVersion?

compileSdkVersion:

  • The compileSdkVersion is the version of API the application is compiled against. You can use Android API features involved in that version of the API (as well as all previous versions).

  • For example, if you try and use API 15 features but set compileSdkVersion to 14, you will get a compilation error. If you set compileSdkVersion to 15 you can still run the app on an API 14 device as long as your app’s execution paths do not attempt to invoke any APIs specific to API 15.

targetSdkVersion:

  • The targetSdkVersion indicates that you have tested your app on (presumably up to and including) the version you specify. This is like a certification or sign-off you are giving the Android OS as a hint to how it should handle your application in terms of OS features.

  • For example, setting the targetSdkVersion value to “11” or higher permits the system to apply a new default theme (Holo) to the application when running on Android 3.0 or higher. It also disables screen compatibility mode when running on larger screens (because support for API level 11 implicitly supports larger screens).

22. Explain about java classes related to the use of sensors on Android.

Android sensor API provides many classes and interface for the use of sensors on Android. The important classes and interfaces of sensor API are given below:

  • Sensor class: This class helps you to create an instance of a specific sensor. It provides methods that let you determine a sensor’s capabilities.

  • SensorManager class: This class is used to create an instance of the sensor service. It provides methods to access and list sensors, to register and unregister sensor listeners, etc.

  • SensorEvent class: This Java class is used to create a sensor event object. It provides information about the sensor event including raw sensor data, the accuracy of data, type of sensor, timestamp of event, etc.

  • SensorEventListener interface: This interface is used to create two callback methods that receive sensor event notifications when sensor value changes or when sensor accuracy changes. Those two methods are void onAccuracyChanged(Sensor sensor, int accuracy) which is called when sensor accuracy is changed and
    void onSensorChanged(SensorEvent event) which is called when sensor values are changed.

23. What is JobScheduler?

The JobSchedular API is used for scheduling different types of jobs against the framework that will be executed in your app’s own process. This allows your application to perform the given task while being considerate of the device’s battery at the cost of timing control.

The JobScheduler supports batch scheduling of jobs. The Android system can combine jobs for reducing battery consumption. JobManager automatically handles the network unreliability so it makes handling uploads easier.

Here is some example of a situation where you would use this job scheduler:

  • Tasks that should be done when the device is connected to a power supply.

  • Tasks that require a Wi-Fi connection or network access.

  • Tasks should run on a regular basis as a batch where the timing is not critical.

24. What are the troubleshooting techniques you can follow if an application is crashing frequently?

If an Android application is crashing frequently, you can follow the below-given techniques:

Compatibility Check:

It is not possible to test an application for all kinds of devices and operating systems. There might be a possibility that an application is not compatible with your OS.

Memory Management:

  • Some apps run perfectly on one mobile device but might crash on other devices. This is where processing power, memory management, and CPU speed are considered.

  • As there is a limited amount of memory space on mobile devices, you can free up memory space for the application to function properly.

  • If an application is frequently crashing, you can delete the application’s data, which will clear its cache memory and allow some free space on your device and might boost the app’s performance.

25. What are containers?

  1. Definition: Containers in Android are special views or layouts that can hold and organize other UI elements.

  2. Organizing Elements: They act like boxes to group and arrange buttons, text fields, and other components neatly on the screen.

  3. Types: Common types include LinearLayout (arranges items in a single line), RelativeLayout (positions items relative to each other), and ConstraintLayout (flexible layout for complex designs).

  4. Hierarchy Structure: Containers create a hierarchy where the outer container holds smaller containers or individual elements, helping to create structured and responsive user interfaces.

  5. Scalability: They make it easier to design UIs that look good on various screen sizes and orientations, ensuring a consistent experience for users across different Android devices.

26. What is the role of Dalvik in Android development?

Dalvik serves as a virtual machine, and it is responsible for running every Android application. Because of Dalvik, a device will have the ability to execute multiple instances of virtual machines efficiently through better memory management.

  1. Explain all topics of TDD in Android in easy way

Certainly! Test-Driven Development (TDD) in Android involves several key topics. Here's an easy explanation of each:

  1. Tests: These are code snippets that check if your app's functionality works as expected. You write tests to define how your code should behave.

  2. Red-Green-Refactor: This is the TDD cycle.

    • Red: Write a test that fails because the code you're testing doesn't exist or doesn't work yet.

    • Green: Write the minimum code necessary to make the test pass. This might not be perfect or efficient code, just enough to pass the test.

    • Refactor: Improve the code while keeping the test green. Refactoring doesn't change behavior; it makes the code cleaner or more efficient.

  3. Unit Tests: These test small, isolated parts (units) of your code, like functions or methods. In Android, you'd typically test individual functions in isolation.

  4. Integration Tests: These test how different parts of your app work together. For Android, this might involve testing activities, fragments, or services in combination.

  5. UI Tests: These simulate user interactions with your app's user interface. You interact with UI elements programmatically to ensure the app behaves as expected.

  6. Mocking: When you don't want to use real components (e.g., a real network call or a real database), you create mock objects. These mimics the real thing but allow you to control their behavior for testing.

  7. Test Doubles: These are objects used in place of real dependencies to isolate the code under test. Common test doubles include mocks, stubs, and fakes.

  8. Arrange-Act-Assert (AAA): A common pattern for structuring tests.

    • Arrange: Set up the test by preparing inputs and test doubles.

    • Act: Perform the action or function you're testing.

    • Assert: Check the expected outcome against the actual result.

  9. Test Runners: These are tools or frameworks that execute your tests. In Android, you often use JUnit as the test runner.

  10. Continuous Integration (CI): This involves automatically running tests whenever code changes are made. It ensures that new code doesn't break existing functionality.

  11. Code Coverage: It measures how much of your code is covered by tests. High code coverage is a goal in TDD to ensure that most of your code is tested.

TDD is a process where you write tests before writing the actual code. It helps catch bugs early, improves code quality, and makes it easier to maintain and extend your Android app.

  1. What is WebRTC?

WebRTC (Web Real-Time Communication) is a technology that allows web browsers and mobile applications to communicate with each other directly in real-time. It is primarily used for features like audio and video calls, file sharing, and live streaming, without needing to install plugins or extra software. Here's an easy way to understand and explain WebRTC for interview preparation:

Key Points About WebRTC:
  1. Purpose:

    • Enables real-time peer-to-peer communication (e.g., voice, video, and data sharing).

    • Eliminates the need for intermediate servers for media streaming.

  2. How It Works:

    • Signaling: WebRTC uses a server (like WebSocket or another signaling mechanism) to exchange connection details and permissions between two users.

    • STUN and TURN Servers: Helps in establishing peer-to-peer connections, especially in cases involving firewalls or NATs.

      • STUN: Finds your public IP address.

      • TURN: Relays data if direct communication fails.

    • Media Streaming: Once connected, users share media (audio/video) directly through the connection.

  3. Core Features:

    • Audio & Video Communication: High-quality streaming.

    • Data Channels: For transferring text, files, or binary data.

    • Encryption: Ensures secure communication using technologies like DTLS (Datagram Transport Layer Security) and SRTP (Secure Real-Time Transport Protocol).

  4. Key Components:

    • getUserMedia(): Captures audio/video from a device.

    • RTCPeerConnection: Manages the connection between peers.

    • RTCDataChannel: Enables data transfer between peers.

  5. Real-World Examples:

    • Video calling apps like Google Meet, Zoom, and Microsoft Teams.

    • Online gaming (low-latency communication).

    • File sharing applications (via peer-to-peer).

Key Benefits:

  • Low Latency: Offers real-time performance.

  • Platform Agnostic: Works across browsers and devices.

  • No Plugins Needed: Built directly into modern web browsers.

Potential Challenges:

  • Network Issues: Difficulties due to NAT traversal and firewalls.

  • Browser Compatibility: Older browsers might not support it.

  • Signaling: Requires additional infrastructure to exchange connection info.

Example Answer for an Interview Question:

What is WebRTC?

WebRTC is a technology that allows real-time peer-to-peer communication, such as audio, video, and data sharing, directly between web browsers and mobile apps. It uses APIs like getUserMedia for capturing media, RTCPeerConnection for managing connections, and RTCDataChannel for sending arbitrary data. It's commonly used in video conferencing apps and ensures secure communication via encryption. WebRTC does rely on signaling servers for initial connection setup and TURN servers for fallback communication in challenging network conditions. It simplifies real-time communication without requiring plugins.

Would you like examples or visual aids to deepen your understanding?

  1. What is Socket.IO?

Socket.IO is a library that simplifies real-time communication between a client (e.g., a web app) and a server. It is often used for real-time updates in web applications, such as chats, notifications, live location tracking, or collaborative tools (like Google Docs).

Key Points About Socket.IO:

  1. Purpose:

    • Enables real-time, bidirectional communication between clients and servers.

    • Perfect for applications that require instant updates or constant communication.

  2. How It Works:

    • Connection Establishment: The client connects to the server using WebSocket as the preferred protocol but falls back to HTTP long polling if WebSocket is unavailable (for compatibility).

    • Event-Based Communication: Communication happens via events that you define (e.g., message, joinRoom, disconnect).

    • Room/Namespace Features:

      • Namespaces: Allow creating multiple channels on the same connection for different types of communication.

      • Rooms: Let clients join groups to receive specific data (e.g., chatrooms).

  3. Core Features:

    • Real-Time Messaging: Instant updates without page reloads.

    • Fallback Mechanism: Uses HTTP long polling if WebSocket is unavailable.

    • Event-Driven: Define custom events for efficient communication (e.g., on("chat"), emit("update")).

    • Broadcasting: Send a message to multiple users at once.

  4. Real-World Examples:

    • Chat Applications: Messages sent instantly between users (e.g., WhatsApp Web, Slack).

    • Live Feeds: Real-time updates in stock price trackers or news apps.

    • Online Multiplayer Games: Synchronizing game states across players.

    • Collaborative Tools: For example, shared whiteboards or real-time text editing.

  5. Key Components:

    • Socket: Represents a single connection between the client and the server.

    • Events: Used to listen to or emit messages between the client and server (e.g., on, emit).

    • Namespaces: Organize communication by grouping sockets under different endpoints.

    • Rooms: Group connections for broadcasting messages (e.g., a specific chat room).

Key Benefits:

  • Simple API: Easy to use with event-driven methods like on() and emit().

  • Cross-Browser Support: Works with all modern browsers.

  • Scalability: Can work with systems like Redis to handle many clients.

Potential Challenges:

  • Latency: While designed for low-latency communication, performance can vary based on the network.

  • Server Overload: Large-scale usage requires proper scaling strategies like clustering.

Example Answer for an Interview Question:

What is Socket.IO?

Socket.IO is a JavaScript library that simplifies real-time, two-way communication between a client and a server. It builds on WebSockets but adds fallbacks like HTTP long polling for broader compatibility. Communication is event-driven, making it easy to implement features like instant chat messages, live notifications, or real-time collaboration tools. For example, you can use socket.emit("message", data) to send a message and socket.on("message") to receive it. It also supports namespaces and rooms to organize communication effectively, making it a go-to solution for real-time web applications.