Android UNIT 2
Android UNIT 2
Services
Service is a component that is used to perform operations on the
background such as downloading files, playing music, handle network
transactions, etc. It doesn't have any UI (user interface). The main aim of a
service is to ensure that the application remains active in the background so
that the user can operate multiple applications at the same time. A service can
run continuously in the background even if the application is closed or the user
switches to another application.
Foreground Service:
A foreground service is used for tasks that are noticeable to the user
and should be given higher priority. Foreground services provide
ongoing notifications to keep the user aware of the ongoing
operation such as playing music, tracking location, and performing
tasks that require ongoing user interaction.
Background Service:
A background service is used for tasks that are less noticeable to the
user and can run silently without showing a persistent notification.
Background services are typically used for tasks like background data
synchronization, updating databases, and performing periodic tasks.
Bound Service
A Bound Service in Android is a type of service that enables various
components within an app, such as activities, to establish connections with
it. This service continues to perform its designated tasks as long as any of
these app components are connected to it. Multiple components can
connect to and interact with a bound service simultaneously. To establish a
connection between an app component and a bound service, the
bindService() method is utilized. This type of service is particularly
suitable for scenarios where ongoing communication and interaction
between app components and a service are required.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
1 onStartCommand()
The system calls this method when another component, such as an activity,
requests that the service be started, by calling startService(). If you implement this
method, it is your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
2 onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-
up.
3
onBind()
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must provide an
interface that clients use to communicate with the service, by returning
an IBinder object. You must always implement this method, but if you don't want to
allow binding, then you should return null.
4
onUnbind()
The system calls this method when all clients have disconnected from a particular
interface published by the service.
5
onRebind()
The system calls this method when new clients have connected to the service, after
it had previously been notified that all had disconnected in its onUnbind(Intent).
6
onDestroy()
The system calls this method when the service is no longer used and is being
destroyed. Your service should implement this to clean up any resources such as
threads, registered listeners, receivers, etc.
Example
Activity_main.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this,"In onstart",Toast.LENGTH_SHORT).show();
Log.i("Info","In oncreate");
}
@Override
protected void onStart(){
super.onStart();
Toast.makeText(this,"In onStart",Toast.LENGTH_SHORT).show();
Log.i("Info","In onStart");
}
@Override
protected void onResume(){
super.onResume();
Toast.makeText(this,"In onResume",Toast.LENGTH_SHORT).show();
Log.i("Info","In onResume");
}
@Override
protected void onPause(){
super.onPause();
Toast.makeText(this,"In onPause",Toast.LENGTH_SHORT).show();
Log.i("Info","In onPause");
}
@Override
protected void onStop(){
super.onStop();
Toast.makeText(this,"In onStop",Toast.LENGTH_SHORT).show();
Log.i("Info","In onStop");
}
@Override
protected void onDestroy(){
super.onDestroy();
Toast.makeText(this,"In onDestroy",Toast.LENGTH_SHORT).show();
Log.i("Info","In onDestroy");
}
}
BROADCAST RECIEVER
A Broadcast Receiver in Android is a mechanism that enables your app to listen and
respond to messages or events sent by the system or other apps. It acts like a listener
that gets triggered when specific things happen, allowing your app to perform actions
or display information in response to those events. Broadcast receivers are commonly
used to respond to system events, such as network changes, battery level changes,
incoming SMS messages, etc. They can also be used to listen for custom broadcasts sent
within your app or even between different apps.
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Example
XML
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
Main.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off",
Toast.LENGTH_SHORT).show();
}
}
A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.
FORM WIDGETS
Form widgets are components that allow users to input data or make selections. These widgets
are used to create interactive forms where users can provide information like text, numbers,
dates, and more. Here are some common form widgets in Android programming:
1. EditText: This widget is used for single-line or multi-line text input. It's commonly used
for fields like names, emails, passwords, etc.
2. TextView: While not a traditional form widget for user input, TextViews are often used
to display labels or instructions next to input fields.
3. Button: Buttons are used to trigger actions, like submitting a form or initiating a search.
4. RadioButton: RadioButton widgets are used for single-choice selections in a group.
Users can select one option out of a list.
5. CheckBox: CheckBoxes allow users to select multiple options from a list. Each checkbox
represents an independent choice.
6. Spinner: Spinners provide a dropdown list of choices. Users can select one option from
the list.
7. DatePicker: DatePicker allows users to select dates from a calendar. It's often used for
birthdates, appointment scheduling, etc.
8. TimePicker: TimePicker allows users to select a specific time, usually for tasks like
setting alarms or reminders.
9. SeekBar: SeekBar widgets let users select a value from a continuous range, often for
things like volume control or brightness adjustments.
10. Switch: Switches are used for binary choices, like turning a setting on or off.
11. AutoCompleteTextView: This widget provides suggestions while users type, which can
help with quickly entering information.
12. RatingBar: RatingBars allow users to rate something on a scale, such as a product or
service.
TEXT FIELDS
Text fields are input fields that allow users to enter text. The primary widget used for
text input is the EditText widget. Here's how you can work with text fields in Android
programming:
TEXT VIEW
TextView is a simple widget that is seen in every android application.
This widget is used to display simple text within the android
application. We can add custom styling to the text that we have to
show
ATTRIBUTES OF TEXT VIEW
android:id: This attribute is used to assign a unique identifier to the TextView element, which
can be referenced in your Java or Kotlin code.
android:text: It sets the text content that will be displayed by the TextView.
android:textSize: This attribute controls the size of the text in the TextView.
android:textStyle: You can use this attribute to make the text bold, italic, or normal.
LAYOUTS
Layouts are used to define the structure and arrangement of user interface components
within an app's user interface. They determine how different widgets, views, and
elements are positioned and displayed on the screen. Android provides various layout
types to help you design your app's user interface effectively. Here are some common
layout types:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
</LinearLayout>
android:id
This is the ID which uniquely identifies the layout.
2. RelativeLayout:
RelativeLayout allows you to position child views relative to each other or the parent
container. It's useful when you want to create complex layouts with views placed in
relation to one another. Using RelativeLayout, you can align two
elements by right border, or make one below another, centered in
the screen, centered left, and so on. By default, all child views are
drawn at the top-left of the layout
ATTRIBUTES OF REALTIVE LAYOUT
android:id: This attribute is used to assign a unique identifier to the RelativeLayout,
which can be referenced in your Java or Kotlin code.
BUTTON CONTROLS
buttons are a fundamental user interface element that users can interact with to trigger actions
or perform tasks in your app.
In your Javacode, you can access the button using its ID and set up a click listener to perform
actions when the button is clicked:
Here's a simple example of how you might create a button and handle its click event:
Xm
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
JAVA
Button myButton = findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform an action when the button is clicked
Toast.makeText(MainActivity.this, "Button Clicked!",
Toast.LENGTH_SHORT).show();
}
});
TOGGLE BUTTONS
Toggle buttons, also known as switch buttons, are UI elements that allow users to switch
between two states, usually represented by "on" and "off" or "enabled" and "disabled".
XML
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle" />
1. Toggle Attributes:
Toggle buttons have various attributes you can customize:
android:textOn: Text to display when the toggle is in the "on" state.
android:textOff: Text to display when the toggle is in the "off" state.
android:checked: Determines the initial state of the toggle.
2. Styling Toggle Buttons:
You can apply custom styles to toggle buttons using XML resources, just like with other
UI elements.
Here's a simple example of how you might create a toggle button and handle its state changes:
XML
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="On"
android:textOff="Off" />
JAVA
ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
if (isChecked) {
// Perform an action when the toggle is switched on
Toast.makeText(MainActivity.this, "Toggle On",
Toast.LENGTH_SHORT).show();
} else {
// Perform an action when the toggle is switched off
Toast.makeText(MainActivity.this, "Toggle Off",
Toast.LENGTH_SHORT).show();
}
}
});
SPINNERS
a Spinner is a user interface element that provides a dropdown list of selectable items. It's
similar to a combo box in other programming frameworks. Users can tap on a Spinner to reveal
the available options and select one. Touching the spinner displays a drop down menu with all
other available values, from which the user can select a new one. Android spinner is associated
with AdapterView. So we need to set the adapter class with the Spinner. Here's how you can
work with Spinners:
package example.abhiandriod.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
String[] Fruits={"Apple","orange","Banana","Mango","Cherry"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
OPTION MENU
An options menu provides a set of actions that users can access by tapping on the
"options" button or icon in the app's toolbar. The options menu is typically used to
provide common actions that are relevant to the current context of the app.
Menu.main.xml
<menu
<item
android:id="@+id/item1"
android:title="Item 1"
app:showAsAction="never" />
<item
android:id="@+id/item2"
android:title="Item 2"
app:showAsAction="never" />
<item
android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="never"
<menu>
<item androidid:”@+id/subitem1”
android:title:=”Sub item1”/>
<item androidid:”@+id/subitem2”
android:title:=”Sub item2”/>
</menu>
</item>
</menu>
Now code for mainactivity.java
package com.example.menu;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu,menu);
return true;
}
}
CONTEXT MENU
A context menu is a floating menu that appears when the user performs a long-click (also known
as a "contextual" or "context" click) on an element. such as a button, list item, or image. Context
menus are used to provide options related to the selected view or the context of the long press.
Mainactivity.java
package com.example.menu;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contextTextView = findViewById(R.id.contextTextView);
registerForContextMenu(contextTextView);
}
@Override
public boolean onCreateContextMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu,menu);
return true;
}
Sub-Menu
Sub menu is basically list of menus inside a menu option. So, sub-menus can
also be called as nested menus. Submenus are used to organize and group menu items,
making it easier for users to access and understand the available options.
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
4. In your res/menu directory, create a new XML file named submenu.xml with the
following content:
Menu.main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:title="Item 1"
app:showAsAction="never" />
<item
android:id="@+id/item2"
android:title="Item 2"
app:showAsAction="never" />
<item
android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="never"
<menu>
<item androidid:”@+id/subitem1”
android:title:=”Sub item1”/>
<item androidid:”@+id/subitem2”
android:title:=”Sub item2”/>
</menu>
</item>
</menu>
MainActivity.java
package com.example.menu;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu,menu);
return true;
}
}
1. Displaying Images:
To display images in your app, you can use the ImageView widget. You can set the
image using a drawable resource or a bitmap. Here's an example:
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image" />
1. In this example, replace @drawable/my_image with the actual resource ID of your image.
2. Loading Images Efficiently:
When working with images, it's important to load them efficiently to avoid memory
issues. You can use libraries like Picasso, Glide, or Coil to help manage image loading,
caching, and resizing.
If we want to add an image we have to copy the name of that image and paste it into the
drawable section res/drawable
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image"
android:layout_centerInParent="true" />
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play Audio"
android:layout_below="@id/imageView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MAINACTIVITY.JAVA
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize MediaPlayer
playButton.setOnClickListener(new View.OnClickListener() {
@Override
mediaPlayer.start();
}
});
@Override
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
ALERT DIALOUGE
an AlertDialog is a common user interface component that displays a small window with a title,
message, and optional buttons. AlertDialogs are used to present information, confirm actions,
and prompt the user for input
You can customize the appearance and behavior of the AlertDialog further by adding custom
views, changing button styles, and more.
Here's a simple Android program that demonstrates how to create and display an
AlertDialog with a title, message, and "OK" button:
android:id="@+id/showAlertButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Alert"
android:layout_centerInParent="true"/>
mainactivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showAlertButton.setOnClickListener(new View.OnClickListener() {
@Override
})
.show();
});
TOAST
Toast is a lightweight notification that provides a simple way to display short messages or
notifications to the user. Toasts appear at the bottom of the screen and are typically used to
convey information that doesn't require the user's immediate attention. They automatically
disappear after a short period of time.
Here's a simple Android program that demonstrates how to use a Toast to display short
messages to the user:
android:id="@+id/showToastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"
android:layout_centerInParent="true"/>
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showToastButton.setOnClickListener(new View.OnClickListener() {
@Override
});
POP UP
, a "pop-up" typically refers to a graphical user interface element that appears on top of
the main content or screen, often used for displaying additional information, options, or
user interactions. There are several ways to implement pop-ups in Android:
<Button
android:id="@+id/showPopupButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Pop-up"
android:layout_centerInParent="true"/>
in the res/layout directory. Add the desired UI elements to this layout. In this example, we'll
create a layout with a TextView and a Button:
xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a custom pop-up" />
<Button
android:id="@+id/closeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close" />
</LinearLayout>
3. In your activity class (usually MainActivity.java or similar), implement the pop-up
functionality:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button showPopupButton =
findViewById(R.id.showPopupButton);
showPopupButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
// Create a custom layout inflater
LayoutInflater inflater =
LayoutInflater.from(MainActivity.this);
View popupView =
inflater.inflate(R.layout.popup_layout, null);