In Android, an application is composed of several key components that work together to create a functional and interactive app. These components manage different aspects of the application’s behavior and interaction with users and other apps.
Activities represent a single screen with a user interface. They are crucial for interacting with users and are often considered the entry points of an application.
Services run in the background to perform long-running operations or tasks without user interaction. They continue to run even if the user switches to another app.
Broadcast receivers listen for and respond to system-wide broadcast announcements or events. They handle events such as incoming calls or system changes.
Content providers manage and share app data with other applications. They provide a standard interface for data access and manipulation across different apps.
Besides the main components, there are other essential elements in Android applications that enhance functionality and user experience.
An Activity in Android is a crucial component that provides the window in which an app draws its user interface (UI). Each activity represents a single screen in an Android application, much like a window or frame in Java. The activity window typically takes up the full screen but can be resized or float over other windows in certain scenarios.
Activities allow developers to place all UI components or widgets in a single screen. Generally, each activity corresponds to one screen of the app. For example, one activity may handle a Preferences screen, while another may manage a Select Photo screen.
The Android Activity Lifecycle refers to the various states that an activity can exist in as it moves between foreground and background or when it gets interrupted by another activity. These states define how an activity behaves and manages its resources. There are four main states:
The activity lifecycle is crucial for managing an Android app's resources efficiently. Understanding these states helps in designing applications that perform well under different conditions, such as interruptions or multitasking. Activities provide the foundation for user interaction by managing the screen, handling user inputs, and maintaining their states as they transition through various lifecycle stages.
We already know that the Android Activity Lifecycle describes the different states an activity goes through from its creation to its destruction. Below is a sample Android program that uses Toast messages to indicate when different lifecycle methods are called. This will help you understand how activities transition through these states.
In this example, we'll implement a simple Android activity that displays a Toast message for each lifecycle method:
package com.example.lifecycleexample;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "Activity Created", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Activity Started", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Activity Resumed", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "Activity Paused", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Activity Stopped", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity Destroyed", Toast.LENGTH_SHORT).show();
}
}
This program demonstrates how to use Toast
messages to track the lifecycle of an
Android
activity. Here’s what each lifecycle method does:
A Started Service ek aisi service hai jo Android me application component (jaise ki Activity) ke through start hoti hai aur independently chalti hai, even agar initiating component destroy ho jaye. Ye un tasks ke liye suitable hai jo app close hone ke baad bhi chalni chahiye (jaise file download karna).
Started Service ko start karne ke liye, startService() call kiya jata hai kisi application component se, jaise Activity ya BroadcastReceiver. Ek baar service start ho jaye, toh wo background me independent tarike se chalti rehti hai, jab tak wo apna task complete nahi kar leti ya phir manually stop na kiya jaye using stopService() ya stopSelf().
Behavior:
Use Case:
Example:
Lifecycle:
startService()
.Bound Service ek aisi service hai jo doosre components (jaise Activity) ko allow karti hai ki wo usse bind ho kar directly interact kar sake via an interface. Service ka lifecycle us component ke lifecycle se tied hota hai jo usse bind karta hai, matlab service tab tak chalti hai jab tak koi component bind hai.
Bound Service ek application component (jaise Activity, Fragment, ya koi aur service) ko bind karne ki facility deti hai using bindService(). Is type ki service ek client-server interface provide karti hai. Client (jo component bind karta hai) service ke saath interact kar sakta hai, requests bhej sakta hai, results le sakta hai, aur communication kar sakta hai.
Behavior:
Use Case:
Example:
Lifecycle:
Socho ek news app hai jo articles background me download kar raha hai. Aapko download ke saath interact karne ki zarurat nahi hai, toh started service background me task ko chalaye rakhegi aur jab tak wo complete nahi hota, ya aap usse stop nahi karte, tab tak chalti rahegi.
Imagine karo ek music app banate waqt, jo user ko playback control (play, pause, skip) allow karta hai app interface se, jabki wo service ke saath continuously interact kar raha hota hai. App service ko bind karega taaki user playback ko UI ke through control kar sake, aur jab user UI band karega, tab service bhi stop ho sakti hai.
A Started Service is a service in Android that is initiated (started) by an application component (like an Activity) and runs independently, even if the initiating component is destroyed. It is suitable for tasks that should continue running even if the user closes the app (e.g., downloading a file).
A Started Service is initiated by calling startService() from an application component like an Activity or BroadcastReceiver. Once started, the service runs in the background independently of the component that started it. It continues to run until it either finishes its task or is explicitly stopped using stopService() or stopSelf().
Behavior:
Use Case:
Example:
Lifecycle:
A Bound Service is a service that allows other components (like an Activity) to bind to it and interact with it directly via an interface. The service lifecycle is tied to the component that is bound to it, meaning the service stops when no components are bound.
A Bound Service allows an application component (like an Activity, Fragment, or another service) to bind to it using bindService(). This type of service provides a client-server interface. The client (the component that binds) can interact with the service, send requests, receive results, and communicate back and forth.
Behavior:
Use Case:
Example:
Lifecycle:
Imagine a news app that downloads articles in the background. You don't need to interact with the download, so a started service runs the task in the background and continues until it's done or you stop it.
Suppose you’re developing a music app that allows the user to control playback (play, pause, skip) from the app interface while continuously interacting with the service. The app would bind to a service so the user can control the playback through the UI, and once the user closes the UI, the service can stop.
Services are helpful for running tasks in the background, such as playing music, downloading files, or handling long-running computations.
In Android, Intents are messaging objects used to communicate between different app components. When it comes to Services, Intents are essential because:
An Intent is a messaging object that allows you to request an action from another component, such as launching an Activity, starting a Service, or delivering a broadcast. Intents can be used to communicate between different components of an application or even between applications.
An Explicit Intent directly specifies the component (usually an Activity or Service) that you want to start. This is useful when you know the class name of the component you want to interact with.
When to use: Explicit Intents are generally used when you want to communicate within your app to start activities, services, or other components.
Example: Starting a new Activity within the same app.
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
In this example, MainActivity.this is the context, and SecondActivity.class is the class of the Activity we want to start.
An Implicit Intent does not specify the component to be started. Instead, it defines an action to be performed, allowing any app that can handle that action to respond.
When to use: Implicit Intents are typically used when you want to communicate outside your app or let the system choose the most appropriate app to handle the task (like sharing content or opening a web page).
Example: Sharing content across apps.
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, check this out!");
startActivity(Intent.createChooser(shareIntent, "Share via"));
In this example, Intent.ACTION_SEND indicates that we want to share some text. The setType() method specifies the type of data being shared, and putExtra() adds the actual text content. The Intent.createChooser() method presents a chooser dialog to allow the user to select an app to share with.
Understanding the Intent Class:
The Intent class in Android is used to perform operations such as starting another Activity or Service. Here’s how it works:
Creating an Intent:
To create an Intent, you typically use the following constructor:
Intent(Context context, Class<?> cls)
Example Usage of Intent:
Now that we know how to create an Intent, let’s look at an example where we use it to navigate between two activities: MainActivity and SecondActivity.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the button in the layout
Button button = findViewById(R.id.button);
// Set an OnClickListener for the button
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create an Explicit Intent to open SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent); // Start SecondActivity
}
});
}
}
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
// Find the button in the layout
Button secBtn = findViewById(R.id.button2);
// Set an OnClickListener for the button
secBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create an Explicit Intent to return to MainActivity
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent); // Start MainActivity
finish(); // Close SecondActivity
}
});
}
}
Explanation of the Example:
Declare SecondActivity in AndroidManifest.xml file:
<activity android:name=".SecondActivity" />
Method Breakdown:
In Android, a Service is a component that runs in the background to perform long-running operations or to perform work for remote processes. Unlike Activities, Services do not have a user interface and can continue running even if the user switches to another application. Understanding the lifecycle of a Service is crucial for managing its operations and resources effectively.
Called when the service is first created. This is where you perform one-time initialization tasks, such as setting up resources.
@Override
public void onCreate() {
super.onCreate();
// Initialization code, e.g., setting up media player
}
In Android, services run in the background to perform long-running tasks, like playing music, downloading files, etc. The onStartCommand() method is part of a Service's lifecycle and is called whenever the service is explicitly started using startService(). It handles the commands sent to the service.
The parameters in onStartCommand():
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Code to execute when the service is started
return START_STICKY; // or START_NOT_STICKY, etc.
}
The Return Value
return super.onStartCommand(intent, flags, startId);
Called when a client binds to the service using bindService(). This method is used for bound services, allowing clients to interact with the service.
It must return an IBinder object. If the service is not intended to be bound, it should return null.
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null; // No binding provided
}
Called when all clients have disconnected from a particular interface published by the service. This can be used to perform cleanup if needed.
@Override
public boolean onUnbind(Intent intent) {
// Code to execute when service is unbound
return super.onUnbind(intent);
}
Called when the service is no longer used and is being destroyed. This is where you should clean up resources, such as stopping threads or releasing resources.
@Override
public void onDestroy() {
super.onDestroy();
// Cleanup code, e.g., stopping media player
}
onCreate()
is called once when the service is created.
onStartCommand()
is called every time the service is
started.onBind()
is called when a client binds to the service;
return null
if not needed.onUnbind()
is called when clients unbind from the
service.onDestroy()
is called when the service is stopped and
needs to release resources.Now that you understand Intents and how they work, let's move on to an example of using an Intent to start a Service. In this case, we will create a Service to play a default ringtone.
Step 1: Create the Service Class
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyRingtoneService extends Service {
private MediaPlayer mPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null; // We don't need to bind this service
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI); // Play default ringtone
mPlayer.setLooping(true); // Loop the ringtone
mPlayer.start(); // Start playing
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId); // Call super method
}
@Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
mPlayer.stop(); // Stop playing
mPlayer.release(); // Release resources
}
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
}
Explanation:
MyRingtoneService
class extends the Service
class.Step 2: Start and Stop the Service from an Activity
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button startButton, stopButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = findViewById(R.id.startServiceBtn);
stopButton = findViewById(R.id.stopServiceBtn);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this, MyRingtoneService.class);
startService(serviceIntent); // Start the service
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent serviceIntent = new Intent(MainActivity.this, MyRingtoneService.class);
stopService(serviceIntent); // Stop the service
}
});
}
}
Explanation:
Step 3: Update the Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/startServiceBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
app:layout_constraintBottom_toTopOf="@+id/stopServiceBtn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.558"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.396" />
<Button
android:id="@+id/stopServiceBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/startServiceBtn"
android:layout_marginBottom="264dp"
android:text="Stop Service"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.554"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Explanation:
Step 4: Declare the Service in AndroidManifest.xml
<service android:name=".MyRingtoneService" />
Explanation:
Summary of the Program:
Step-by-Step Explanation of a Bound service
Example: Bound Service for Generating Random Numbers
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import androidx.annotation.Nullable;
import java.util.Random;
public class BoundedService extends Service {
private Random noGenerator = new Random();
public BoundedService(){}
// IBinder object to interact with the service
private IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
BoundedService getService(){
return BoundedService.this;
}
}
// This is where the client (Activity) binds to the service
@Nullable
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
// A method that returns a random number
public int getRandom(){
return noGenerator.nextInt(100);
}
}
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
BoundedService bService; // Reference to the bound service
Intent myIntent; // Intent for binding to the service
boolean bound = false; // Tracks if the service is bound
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view){
// Binding the service
myIntent = new Intent(MainActivity.this, BoundedService.class);
bindService(myIntent, sConnection, Context.BIND_AUTO_CREATE); // Automatically create and bind service
Toast.makeText(MainActivity.this, "Service Bounded", Toast.LENGTH_SHORT).show();
}
// ServiceConnection object that manages the connection with the service
private ServiceConnection sConnection= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
BoundedService.LocalBinder myBinder = (BoundedService.LocalBinder) iBinder;
bService = myBinder.getService(); // Get service instance
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
bound = false;
}
};
public void stopService(View view){
// Unbind the service
unbindService(sConnection);
Toast.makeText(MainActivity.this, "Service UnBounded", Toast.LENGTH_SHORT).show();
bound = false;
}
public void displayRandomNumber(View view){
if(bound){
// Use the bound service to generate a random number
int i = bService.getRandom();
Toast.makeText(MainActivity.this, "" + i, Toast.LENGTH_SHORT).show();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.2"
android:onClick="startService" />
<Button
android:id="@+id/btn_stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_start_service"
app:layout_constraintVertical_bias="0.2"
android:onClick="stopService" />
<Button
android:id="@+id/btn_display_random_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Random Number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn_stop_service"
app:layout_constraintVertical_bias="0.2"
android:onClick="displayRandomNumber" />
</androidx.constraintlayout.widget.ConstraintLayout>
Add the following in AndroidManifest.xml file:
<service android:name=".BoundedService" />
In this example:
First we should know about Broadcast.
How Broadcasts Work?
Jab ek broadcast bheja jata hai, toh ye ya to ordered ho sakta hai (ek receiver ko ek time pe, priority ke order mein deliver hota hai) ya unordered ho sakta hai (sabhi receivers ko ek saath deliver hota hai).
System broadcasts Android mein woh implicit intents hote hain jo operating system bhejta hai apps ko notify karne ke liye jab kuch system-wide events hote hain. Ye broadcasts system ki state ya environment mein hone wale changes ko signal karte hain, jaise device ka boot hona, power connect/disconnect status, airplane mode ka toggle hona, and many more. Apps in system events ko sunne ke liye broadcast receivers register kar sakti hain, ya to statically (AndroidManifest.xml ke through) ya dynamically (code ke through). In broadcasts ko samajhna aur use karna apps ko system changes ke according react karne mein madad karta hai, jisse user experience aur bhi responsive aur efficient hota hai.
Following are some broadcast intents which Android uses to monitor system and environmental state changes
abortBroadcast()
.
Now Let's talk about Broadcast Receivers
Broadcast Intent
Intent Filters
Broadcast receivers ko aam taur par do tareekon se banaya jaata hai:
Steps:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.POWER_CONNECTED"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
// Steps track karna ya data sync karna shuru karo
Toast.makeText(context, "Boot completed! Starting fitness tracking.", Toast.LENGTH_SHORT).show();
} else if (Intent.ACTION_POWER_CONNECTED.equals(action)) {
// Power connected event handle karo
Toast.makeText(context, "Power connected!", Toast.LENGTH_SHORT).show();
}
}
}
Steps:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MyBroadcast myBroadcast = new MyBroadcast();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
// IntentFilter create karo taaki receiver ko specify karo ki kis event ko sunna hai
IntentFilter myIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
// BroadcastReceiver ko register karo Bluetooth state changes ko sunne ke liye
registerReceiver(myBroadcast, myIntent);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(myBroadcast);
}
}
package com.example.myapplication;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
// Ye class BroadcastReceiver ko extend karti hai, jo app ko system-wide broadcast events ko respond karne mein madad karti hai.
public class MyBroadcast extends BroadcastReceiver {
// onReceive method tab call hota hai jab BroadcastReceiver ko koi broadcast milta hai.
@Override
public void onReceive(Context context, Intent intent) {
// Broadcast Intent se action nikaalo (yahan Bluetooth state changes ke liye interested hain).
String action = intent.getAction();
// Check karo ki action Bluetooth state changes se related hai ya nahi.
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
// Intent se Bluetooth state nikaalo (ye integer value hogi).
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
// Bluetooth states ko handle karne ke liye switch statement use karo.
switch (state) {
// Agar Bluetooth on hai, toh "Bluetooth ON" message show karo.
case BluetoothAdapter.STATE_ON:
Toast.makeText(context, "Bluetooth ON", Toast.LENGTH_SHORT).show();
break;
// Agar Bluetooth off hai, toh "Bluetooth OFF" message show karo.
case BluetoothAdapter.STATE_OFF:
Toast.makeText(context, "Bluetooth OFF", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
getAction()
method use karke broadcast ka type retrieve karte hain. Is
example mein receiver check karta hai
agar action BluetoothAdapter.ACTION_STATE_CHANGED
hai, matlab Bluetooth
state change hua hai.
getIntExtra()
method Bluetooth state (e.g., ON, OFF) nikaalne ke liye use
hota hai.
BluetoothAdapter.EXTRA_STATE
key state ko access karne ke liye use hoti
hai, aur
BluetoothAdapter.ERROR
fallback value ke liye hoti hai.
Receiver Ko Unregister Karna
unregisterReceiver(myBroadcast);
First we should know about Broadcast.
How Broadcasts Work?
When a broadcast is sent, it can either be ordered (delivered to one receiver at a time, in priority order) or unordered (delivered to all receivers simultaneously).
System broadcasts in Android are implicit intents sent by the operating system to notify apps of certain system-wide events. These broadcasts signal changes in the system's state or environment, such as device booting up, power connection status, airplane mode toggling, and more. Apps can register broadcast receivers to listen for these system events, either statically (via the AndroidManifest.xml) or dynamically (via code). Understanding and using these broadcasts helps apps to react accordingly to system changes, providing a more responsive and efficient user experience.
Following are some broadcast intents which Android uses to monitor system and environmental state changes
Now Let's talk about Broadcast Receivers
Broadcast Intent
Intent Filters
Broadcast receivers are typically created in two ways:
Steps:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.POWER_CONNECTED"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
// Start tracking steps or syncing data
Toast.makeText(context, "Boot completed! Starting fitness tracking.", Toast.LENGTH_SHORT).show();
} else if (Intent.ACTION_POWER_CONNECTED.equals(action)) {
// Handle power connected event
Toast.makeText(context, "Power connected!", Toast.LENGTH_SHORT).show();
}
}
}
Steps:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MyBroadcast myBroadcast = new MyBroadcast();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
// Create an IntentFilter to specify what the receiver should listen for
IntentFilter myIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
// Register the BroadcastReceiver to start listening for Bluetooth state changes
registerReceiver(myBroadcast, myIntent);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(myBroadcast);
}
}
package com.example.myapplication;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
// This class extends BroadcastReceiver, which allows the app to respond to system-wide broadcast events.
public class MyBroadcast extends BroadcastReceiver {
// The onReceive method is called when the BroadcastReceiver receives a broadcast event.
@Override
public void onReceive(Context context, Intent intent) {
// Get the action from the broadcast Intent (in this case, we're interested in Bluetooth state changes).
String action = intent.getAction();
// Check if the action is related to Bluetooth state changes.
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
// Get the Bluetooth state from the intent (the state will be an integer value).
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
// Use a switch statement to handle different Bluetooth states.
switch (state) {
// If Bluetooth is turned on, show a "Bluetooth ON" message.
case BluetoothAdapter.STATE_ON:
Toast.makeText(context, "Bluetooth ON", Toast.LENGTH_SHORT).show();
break;
// If Bluetooth is turned off, show a "Bluetooth OFF" message.
case BluetoothAdapter.STATE_OFF:
Toast.makeText(context, "Bluetooth OFF", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
getAction()
method is used to retrieve the type of broadcast. In this
example, the receiver checks
if the action is BluetoothAdapter.ACTION_STATE_CHANGED
, indicating a
Bluetooth
state change.
getIntExtra()
method extracts the Bluetooth state (e.g., ON, OFF) from
the
broadcast's intent.
The key BluetoothAdapter.EXTRA_STATE
is used to access the state, and
BluetoothAdapter.ERROR
serves as a fallback value.
Unregistering the Receiver
unregisterReceiver(myBroadcast);
In Android, a View is the basic building block of the user interface. Every element you see on the screen, whether it's a button, an image, or a text field, is a type of View. Views define how the content should be displayed and how the user can interact with it. Android's View class is the parent class for all UI components (like buttons, text views, etc.).
Characteristics of Views:
Basic View Types:
Attributes of a View:
Interacting with Views:
Now we will try to understand each view one by one.
A Button is a view that users can tap to perform actions. It is one of the most common UI elements used for interacting with the app. Buttons are often used to trigger events like submitting a form, navigating to another screen, or starting a process.
XML Definition:
<Button
android:id="@+id/button_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="onButtonClick" />
This XML code defines a simple button with the text "Click Me" displayed on it. The android:onClick attribute is used to specify a method in your activity that will be called when the button is clicked.
Attributes of Button:
Example:
public void onButtonClick(View view) {
// Perform action on button click
Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show();
}
In this code example, the
Another way of performing something by clicking the Button:
Button buttonExample = findViewById(R.id.button_example);
buttonExample.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show();
}
});
In this example, the button is assigned a click listener using setOnClickListener. When the user clicks the button, a Toast message is displayed.
Button Events:
Edit Text is a user interface element that allows users to enter and modify text. It is commonly used for forms, search fields, and any place where user input is required. Edit Text provides various input types and attributes to customize its behavior and appearance.
XML Definition:
<EditText
android:id="@+id/edit_text_example"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text here" />
This XML code defines an Edit Text field with a hint "Enter text here" displayed when the field is empty. The user can input text into this field.
Attributes of Edit Text:
Example:
EditText editTextExample = findViewById(R.id.edit_text_example);
String userInput = editTextExample.getText().toString();
Toast.makeText(getApplicationContext(), userInput, Toast.LENGTH_SHORT).show();
In this code example, the Edit Text is referenced by its ID, and the text entered by the user is retrieved using getText(). This text is then displayed in a Toast message when you want to show it, for example, after a button click.
Example Use Case:
Edit Text fields are commonly used in login forms, search bars, and anywhere users need to input text. For example, a user can enter their name, email address, or any other information required by the application.
A Radio Button is a user interface element that allows users to select one option from a set of choices. Radio buttons are typically used when a user needs to choose a single option among multiple alternatives, such as selecting a gender, payment method, or preferences.
XML Definition:
<RadioGroup
android:id="@+id/radio_group_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_button_option1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<RadioButton
android:id="@+id/radio_button_option2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
</RadioGroup>
This XML code defines a RadioGroup that contains two radio buttons: "Option 1" and "Option 2." The RadioGroup ensures that only one radio button within the group can be selected at any time.
Attributes of Radio Button:
Example:
RadioGroup radioGroup = findViewById(R.id.radio_group_example);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton selectedRadioButton = findViewById(checkedId);
String selectedText = selectedRadioButton.getText().toString();
Toast.makeText(getApplicationContext(), "Selected: " + selectedText, Toast.LENGTH_SHORT).show();
}
});
In this code example, a listener is set on the RadioGroup to detect when a radio button is selected. The onCheckedChanged method retrieves the selected radio button and displays its text in a Toast message.
Example Use Case:
Radio buttons are commonly used in forms where the user must select a single option, such as gender (Male/Female), or preferences like subscription plans (Basic/Premium). They enhance user experience by ensuring that only one choice can be selected at a time.
An Image View is a user interface element that displays images in an Android application. It is commonly used to show graphics, logos, or photos. Image View can load images from various sources, including drawable resources, files, or URLs.
XML Definition:
<ImageView
android:id="@+id/image_view_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/sample_image" />
This XML code defines an Image View that displays an image resource named "sample_image" from the drawable folder. The width and height are set to wrap the content of the image.
Attributes of Image View:
Java Code Example:
ImageView imageViewExample = findViewById(R.id.image_view_example);
imageViewExample.setImageResource(R.drawable.new_image);
In this code example, the Image View is referenced by its ID, and the image displayed is changed to "new_image" from the drawable resources using the setImageResource() method.
Example Use Case:
Image Views are commonly used for displaying profile pictures, icons, or any other graphics in your application. They enhance the visual appeal and usability of your app by providing relevant images.
A Toast is a small message that pops up on the screen for a short duration, providing feedback to the user. Unlike a dialog, a toast does not block user interaction with the app, making it useful for showing non-intrusive messages like "Task completed," "Network error," or "File saved successfully."
In Android, a Toast
message can be created and displayed using the following syntax:
Toast.makeText(context, message, duration).show();
Let’s break this down:
this
or getApplicationContext()
."Hello, World!"
.Toast.LENGTH_SHORT
: Displays the toast for a short period (~2 seconds).
Toast.LENGTH_LONG
: Displays the toast for a longer period (~3.5 seconds).
Toast.makeText(this, "Hello, World!", Toast.LENGTH_SHORT).show();
Step-by-Step Explanation:
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
Button myBtn = findViewById(R.id.button);
myBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
i = i + 1;
Toast.makeText(MainActivity.this, "No. of times button is clicked = " + i , Toast.LENGTH_SHORT).show();
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toast Demo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.486"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.091" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#5DE063"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.584" />
</androidx.constraintlayout.widget.ConstraintLayout>
A List View is a user interface element that displays a scrollable list of items. It is used to show multiple items in a single view, allowing users to scroll through the list and select individual items. List Views are commonly used for displaying data in a structured format, such as contact lists, email inboxes, or product listings.
XML Definition:
<ListView
android:id="@+id/list_view_example"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
This XML code defines a List View that takes up the full width of the parent and adjusts its height according to the content.
Attributes of List View:
wrap_content
or match_parent
.wrap_content
or match_parent
.To populate a List View, an adapter is required to connect the List View to the data source. The adapter creates a view for each item in the data set and binds the data to those views.
Example Code for List View with ArrayAdapter:
ListView listViewExample = findViewById(R.id.list_view_example);
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
listViewExample.setAdapter(adapter);
Example: Using ArrayAdapter to Display a List of Strings
Step 1: Add ListView in XML Layout
<ListView
android:id="@+id/myListXML"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
Step 2: Create the Activity Class
package com.example.mybcaadapter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView myListView;
String myArr[] = {"GEHU-BHIMTAL", "GEHU-HLD", "GEHU-DDN"}; // Array of strings
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Reference the ListView from the layout
myListView = findViewById(R.id.myListXML);
// Create an ArrayAdapter to bind the data to the ListView
ArrayAdapter myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, myArr);
myListView.setAdapter(myAdapter); // Set the adapter for the ListView
}
}
Explanation of the Code:
This example demonstrates how to create a ListView in Android, bind data using an ArrayAdapter, and display a simple list of items.
A Grid View is a user interface element that displays items in a two-dimensional grid. It is used when you want to present data in a tabular format, allowing users to see multiple items simultaneously. Grid Views are commonly used for displaying images, product listings, or any data that benefits from a grid layout.
Similar to List Views, Grid Views also require an adapter to populate the grid with items. The adapter defines how each item will be displayed in the grid format.
XML Definition:
<GridView
android:id="@+id/grid_view_example"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2" />
This XML code defines a Grid View that occupies the full width of the parent and adjusts its height based on the content. The numColumns attribute specifies the number of columns in the grid.
Attributes of Grid View:
Java Code Example:
GridView gridViewExample = findViewById(R.id.grid_view_example);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
gridViewExample.setAdapter(adapter);
In this code example, an ArrayAdapter is used to populate the Grid View with a list of items. The Grid View is referenced by its ID, and the adapter binds the data to the Grid View.
Example Use Case:
Grid Views are commonly used for displaying images, such as photo galleries, icon sets, or product thumbnails. They provide an organized layout that allows users to view multiple items at once.
In summary, the Grid View view is essential for presenting data in a structured format, enhancing user experience by providing a visually appealing layout for multiple items.
A Spinner in Android is a UI element that allows users to select an item from a dropdown menu. It is similar to a dropdown list in web development and is often used when you want to provide users with multiple choices in a compact view. When a Spinner is tapped, it shows a list of options, and the selected item is displayed in the Spinner view.
XML Definition:
<Spinner
android:id="@+id/spinner_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This XML code defines a Spinner that adjusts its width and height according to its content.
Java Code Example:
// Define the Spinner
Spinner spinnerExample = findViewById(R.id.spinner_example);
// Create an array of options for the Spinner
String[] items = { "Option 1", "Option 2", "Option 3" };
// Create an ArrayAdapter to populate the Spinner with items
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
// Set the adapter to the Spinner
spinnerExample.setAdapter(adapter);
// Handle Spinner item selection
spinnerExample.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
// Do something with the selected item
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Optional: Handle case when no item is selected
}
});
In this example, the Spinner is populated with an array of items using an ArrayAdapter. The setOnItemSelectedListener() method is used to handle the action when a user selects an item from the dropdown list.
Attributes of Spinner:
Example Use Case:
Spinners are commonly used in forms where users need to select an option from a predefined list, such as selecting a country, choosing a category, or picking a time range. They provide a clean and space-efficient way to present multiple options.
A ToggleButton in Android is a user interface element that acts like a switch. It allows the user to toggle between two states: ON and OFF. It's similar to a CheckBox but provides a visual toggle to indicate the state of the button.
XML Definition:
<ToggleButton
android:id="@+id/toggle_button_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="ON"
android:textOff="OFF" />
This XML code defines a ToggleButton with two states: "ON" and "OFF". When the button is in the ON state, it shows the "ON" text, and when in the OFF state, it shows the "OFF" text.
Java Code Example:
// Define the ToggleButton
ToggleButton toggleButton = findViewById(R.id.toggle_button_example);
// Set an OnClickListener to handle state changes
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled (ON)
Toast.makeText(getApplicationContext(), "Toggle is ON", Toast.LENGTH_SHORT).show();
} else {
// The toggle is disabled (OFF)
Toast.makeText(getApplicationContext(), "Toggle is OFF", Toast.LENGTH_SHORT).show();
}
}
});
In this example, the ToggleButton is controlled using the setOnCheckedChangeListener()
method, which handles the state change (ON/OFF). A Toast message is displayed depending on the state
of the button.
Attributes of ToggleButton:
wrap_content
or match_parent
.Example Use Case:
A ToggleButton is typically used for settings, where you want to allow the user to enable or disable a feature (like turning on/off Wi-Fi, sound, or notifications).