Main components of android application
Tags: kotlin, android, androiddev, mobile
Published: 2024-06-19 08:01:06

## Application Components

Application components are the essential building blocks of an Android application. Each component is a different point through which the system can enter your application. Not all components are actual entry points for the user and some depend on each other, but each one exists as its own entity and plays a specific role—each one is a unique building block that helps define your application’s overall behavior.

---

## Activities

> An activity represents a single, full-screen user interface (UI) within your application.

Each activity focuses on a specific task or feature, providing a cohesive and focused experience for the user.   It's the primary touchpoint for user interaction within your application.

> To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: `onCreate()`, `onStart(`), `onResume()`, `onPause()`, `onStop()`, and `onDestroy()`. The system invokes each of these callbacks as an activity enters a new state.


Here's a basic example of an activity written in Kotlin:

```
class MainActivity : Activity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
  }
}
```
This code defines a `MainActivity `class that inherits from the Activity class. The `onCreate `method, overridden here, is called when the activity is first created. This is where you would typically inflate your layout (the visual design of the screen) using `setContentView `and set up UI elements for user interaction.

<u>**Key Points:**

- Activities manage the application's lifecycle, meaning they are created, paused, resumed, and destroyed as the user navigates through the app.
- Each activity is independent, allowing different applications to potentially launch specific activities within your app (if permissions allow).
- For a more feature-rich UI, activities often work together, passing data and triggering actions between them.
- Activities can handle user input through UI elements like buttons, text fields, and touch gestures.
- They can also launch other activities or system services within the Android framework.

---

## Services
> A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface.

Unlike activities, **services run in the background to perform long-running operations or tasks for remote processes.** They don't provide a UI directly. 
A service can be started, bound, or both:

>1. Started
>>A service is "started" when an application component (such as an activity) starts it by calling `startService()`. Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself. The service runs indefinitely and must stop itself by calling `stopSelf()`. Another component can also stop the service by calling `stopService()`. When the service is stopped, the system destroys it.

>2. Bound
>>A service is "bound" when an application component binds to it by calling `bindService()`. A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed. The service is created when another component (a client) calls `bindService()`. The client then communicates with the service through an `IBinder` interface. The client can close the connection by calling `unbindService()`. Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. The service does not need to stop itself.

>3. Foreground
>>A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app. Although both Activities and Services can be killed if the system is low on memory, a foreground service has priority over other resources. To request that a service run in the foreground, call `startForeground()` instead of `startService()`.




Here's a simplified example of a service:

```
class MyService : Service() {

  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    // Perform background task here
    return START_STICKY
  }
}

```
This code defines a `MyService `class that extends the `Service `class. The `onStartCommand` method is called when the service is started, typically by an `activity` or another component. This is where you would place your background operations, like playing music or fetching data from a network.

**<u>Key Points:</u>**

- Services are ideal for long-running tasks that shouldn't be interrupted by the user interacting with the UI.
- They can be started, stopped, or bound to by other components in your application.
- There are different service lifecycle methods to handle various scenarios, such as when the system is running low on memory.
- Services can run even when the user is not actively using the application, as long as the system allows it.
- They can communicate with activities or other components through mechanisms like intents or binders.

---

## Broadcast Receivers

> Broadcast receivers are lightweight components that listen for system-wide broadcast announcements.
 
Broadcasts are messages that the Android system and Android apps send when events occur that might affect the functionality of other apps. These announcements can originate from the system itself (e.g., low battery) or from other applications. 

There are two types of broadcasts:
1. System broadcasts are delivered by the system.
2. Custom broadcasts are delivered by your app.

Apps can receive broadcasts in two ways:
1. Manifest-declared receivers
2. Context-registered receivers

> There are two kinds of Broadcast Receivers.
1. Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even if the app is closed.
2. Dynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized.




Here's an example of a broadcast receiver:

```
class BatteryLevelReceiver : BroadcastReceiver() {

  override fun onReceive(context: Context, intent: Intent) {
    val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
    // Handle low battery level if needed
  }
}
```
**<u>Key Points:</u>**

- Broadcast receivers are event-driven, meaning they are triggered only when a specific broadcast is sent. This makes them efficient for reacting to system changes or application events without constantly monitoring the system state.
- They are lightweight and have a simple lifecycle, making them suitable for short-lived tasks like updating the UI based on a broadcast.
- Broadcast receivers can be registered dynamically at runtime or declared statically in the Android Manifest file. This allows for flexibility in how you choose to listen for broadcasts.
- They cannot directly interact with the UI themselves. However, they can trigger actions within activities or services that can then update the UI or perform other necessary actions.
- Broadcast receivers can be permission-protected, ensuring that only authorized applications can receive specific broadcasts.

---

## Content Providers
Content providers act as a central hub for managing shared sets of application data. They allow other applications to access and potentially modify this data, if your content provider grants permission. 
> These are handled by the class ContentResolver class. This class implements a set of APIs(Application Programming Interface) that enables the other applications to perform the transactions. Any Content Provider must implement the Parent Class of ContentProvider class. 

Here's a peek at a content provider :

```
class NoteProvider : ContentProvider() {

  override fun onCreate(): Boolean {
    // Initialize content provider
    return true
  }

  // Implement methods for querying and modifying data
}
```
This code defines a `NoteProvider` class extending the `ContentProvider `class. The `onCreate `method is used for initialization. Content providers offer a standard set of methods for other applications to interact with the data, including querying for specific information or updating existing data.


**<u>Key Points:</u>**

- Content providers are useful for sharing data between your application and others, enabling functionalities like contact access or data exchange.
- They can also be used for private data management within your application.
- Security is crucial when dealing with content providers, as you control access permissions for other applications.
- Content providers offer a structured way to access and modify data, often using a relational database model.
- They can be used to synchronize data between your application and other applications or services.

## Conclusion
In conclusion, Android applications are built upon four fundamental components: activities, services, content providers, and broadcast receivers.

**Activities** represent individual screens with user interfaces, providing the primary touchpoint for user interaction.
**Services** handle long-running background tasks, operating independently of the UI.
**Content providers** manage shared sets of data, enabling data exchange between your application and others.
**Broadcast receivers** act as event listeners, responding to system-wide announcements and triggering appropriate actions.