CHP 5 Mad Services Modified

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Services in Android are a special component that facilitates an

application to run in the background in order to perform long-running


operation tasks.
 The prime 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.
Further, application components can bind itself to service to carry out
inter-process communication(IPC)
There is a major difference between android services and threads
Thread is a feature provided by the Operating system to allow the user
to perform operations in the background.
While service is an android component that performs a long-running
operation about which the user might not be aware of as it does not
have UI.
Types of Android Services
1. Foreground Services:
Services that notify the user about its ongoing operations are termed
as Foreground Services. Users can interact with the service by the
notifications provided about the ongoing task. Such as in downloading a
file, the user can keep track of the progress in downloading and can also
pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These
services do not notify the user about ongoing background tasks and
users also cannot access them. The process like schedule syncing of
data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application
like activity to bound themselves with it. Bound services perform their
task as long as any application component is bound to it. More than one
component is allowed to bind themselves with a service at a time. In
order to bind an application component with a service bindService()
method is used.
The Life Cycle of Android
Services
In android, services have 2 possible paths to complete its life cycle
namely Started and Bounded.
1. Started Service (Unbounded Service):
By following this path, a service will initiate when an application
component calls the startService() method. Once initiated, the service
can run continuously in the background even if the component is
destroyed which was responsible for the start of the service.
Two option are available to stop the execution of service:
By calling stopService() method,
The service can stop itself by using stopSelf() method.
2. Bounded Service:
It can be treated as a server in a client-server interface. By following
this path, android application components can send requests to the
service and can fetch results.
A service is termed as bounded when an application component binds
itself with a service by calling bindService() method.
To stop the execution of this service, all the components must unbind
themselves from the service by using unbindService() method.
To carry out a downloading task in the background, the startService()
method will be called. Whereas to get information regarding the
download progress and to pause or resume the process while the
application is still in the background, the service must be bounded with
a component which can perform these tasks.
A user-defined service can be created through a normal class which is
extending the class Service. Further, to carry out the operations of
service on applications, there are certain callback methods which are
needed to be overridden. The following are some of the important
methods of Android Services:
1. onStartCommand():
The Android service calls this method when a component(eg: activity)
requests to start a service using startService().
Once the service is started, it can be stopped explicitly using
stopService() or stopSelf() methods.
2. onBind()
This method is mandatory to implement in android service and is
invoked whenever an application component calls the bindService()
method in order to bind itself with a service. User-interface is also
provided to communicate with the service effectively by returning an
IBinder object.
If the binding of service is not required then the method must return
null.
3. onUnbind()
The Android system invokes this method when all the clients
get disconnected from a particular service interface.
onRebind()
Once all clients are disconnected from the particular interface of service
and there is a need to connect the service with new clients, the system
calls this method.
onCreate()
Whenever a service is created either using onStartCommand() or
onBind(), the android system calls this method. This method is
necessary to perform a one-time-set-up.
onDestroy()
When a service is no longer in use, the system invokes this method
just before the service destroys as a final clean up call. Services must
implement this method in order to clean up resources like registered
listeners, threads, receivers, etc.
<?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"
android:background="#168BC34A"
tools:context=".MainActivity">
<LinearLayout

android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
android:fontFamily="@font/roboto"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
<Button

android:id="@+id/startButton"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginStart="20dp"

android:layout_marginTop="10dp"

android:layout_marginEnd="20dp"

android:layout_marginBottom="20dp"

android:background="#4CAF50"

android:fontFamily="@font/roboto"

android:text="@string/startButtonText"

android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Display1"

android:textColor="#FFFFFF"

android:textStyle="bold" />
<Button

android:id="@+id/stopButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:text="@string/stopButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
app:srcCompat="@drawable/banner" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity file
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 implements
View.OnClickListener {
// declaring objects of Button class
private Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// assigning ID of startButton
// to the object start
start = (Button) findViewById( R.id.startButton );
// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );
// declaring listeners for the
// buttons to make them respond
// correctly according to the process
start.setOnClickListener( this );
stop.setOnClickListener( this );
}
public void onClick(View view) {
// process to be performed
// if start button is clicked
if(view == start){
// starting the service
startService(new Intent( this, NewService.class ) );
}
// process to be performed
// if stop button is clicked
else if (view == stop){
// stopping the service
stopService(new Intent( this, NewService.class ) );
} }}
Service class.
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
public class NewService extends Service {
// declaring object of MediaPlayer
private MediaPlayer player;
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI );
player.setLooping( true );
player.start();
return START_STICKY;
}
public void onDestroy() {
super.onDestroy();
// stopping the process
player.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

You might also like