0% found this document useful (0 votes)
68 views

Lab - 3b - Android Service

This document provides instructions for creating an Android service that plays background music. It includes: 1) An overview of services and their lifecycle methods like onStartCommand(), onBind(), onCreate(), and onDestroy(). 2) Steps to create a service class that extends Service and implements these methods, with an example of a service that plays the default ringtone on a loop. 3) Instructions on defining the service in the Android manifest and starting/stopping it from an activity using startService() and stopService().

Uploaded by

Aisya Zuhudi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Lab - 3b - Android Service

This document provides instructions for creating an Android service that plays background music. It includes: 1) An overview of services and their lifecycle methods like onStartCommand(), onBind(), onCreate(), and onDestroy(). 2) Steps to create a service class that extends Service and implements these methods, with an example of a service that plays the default ringtone on a loop. 3) Instructions on defining the service in the Android manifest and starting/stopping it from an activity using startService() and stopService().

Uploaded by

Aisya Zuhudi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

SKR4307: Mobile Applications

Sem. II 2019/20
Lab 3b: Android Service

Introduction

Service is a process, but the special thing is about the service is it doesn’t need user
interaction and it runs on background. E.g., like playing music in background. It is a long
running process and it does not need user interaction.

Figure 1: Android Service Lifecycle

1
1. Android service

To create a service, we need to create a normal class extending the class Service. And
need to override the following methods as shown in Figure 1:

onStartCommand()
 The method is invoked when the service is started using
the startService() method. The method startService() can be called
from any activity and it will request the service to start.

onBind()
 The method is called when to bind the service with an activity. The service can result
back something to the activity after binding. But if do not want to bind the service
with activity, just return null on this method.

onCreate()
 This method is called when the service is created.

onDestroy()
 When the service is no longer used and destroyed this method is called by the system.

2. Defining it on Manifest

 Need to define the service in AndroidManifest.xml file. It is very important.

<service android:name=”.ServiceName” />

 Put the above code inside the application tag for every service.

3. Creating Android Service Tutorial

Step 1: Create a new Android project


a. Application name: AndroidServiceExample
b. Create an Empty Activity with the following configuration:
 Activity Name: MainActivity.java
 Layout Name: activity_main.xml

Step 2: Open the activity_main.xml layout file

 The activity_main.xml layout file contain two Button UI as follows:

2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:orientation="vertical"
tools:ignore="RtlCompat">

<Button
android:id="@+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Start Service" />

<Button
android:id="@+id/btnStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Stop Service" />

</LinearLayout>
</RelativeLayout>

Figure 2: activity_main.xml layout

Step 3: Rewrite the MainActivity.java file

3
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//Button objects
private Button buttonStart;
private Button buttonStop;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Getting buttons from xml


buttonStart = (Button)findViewById(R.id.btnStart);
buttonStop = (Button)findViewById(R.id.btnStop);

//Attaching onClicklistener to object button


buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);

}
@Override
public void onClick(View view) {
if(view == buttonStart){
//Start the service here
} else if (view == buttonStop) {
//Stop the service here
}
}
}

Step 4: Create a new service


 Create a new class extending Service.
 Create the following class MyService.java.

import android.app.Service;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.provider.Settings;

4
import android.support.annotation.Nullable;

public class MyService extends Service {

//Create a mediaplayer object

private MediaPlayer player;

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Getting system default ringtone

player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);

//Setting loop play to true

player.setLooping(true);

//Starting the player


player.start();

//Service will be explicity started and stopped


return START_STICKY;
}

@Override
public void onDestroy() {
super.onDestroy();

//Stop the player when service is destroyed


player.stop();
}
}

 Simply playing the default ringtone inside the onStartCommand() method.


 When start this service the default ringtone will start ringing on loop until don’t stop the
service.

Step 5: Defining service in Manifest.

 Before starting the service, need to define it inside AndroidManifest.xml.


 Modify manifest file as below.

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abdulrahimanamirrizaan.androidserviceexample">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"

5
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>

<!-- Define the service class -->


<service android:name=".MyService"/>

</application>

</manifest>

Step 6: Starting and Stopping Service


 Inside MainActivity.java modify the onClick(View view) method to
start and stop the service as follows:

When button start is clicked:


startService(new Intent(this, MyService.class));

When button stop is clicked:


stopService(new Intent(this, MyService.class));

Step 7: Run the app

 Now run the app.


 When tap on Start Service button, the ringtone will start ringing.
o And even if close your application ringtone will keep ringing.
o Because it is playing with a Service that runs on background.
 To stop it you have to stop the service using Stop Service button.

Step 8: Add toast functions

Add toast functions to your code, so that everytime you click on the Start Service and Stop
Service buttons, a message will appear denoting either “Your service has started” or “Your
service has stopped”.

6
Additional exercise:

Go to this website: https://www.vogella.com/tutorials/AndroidServices/article.html

Implement instructions no. 6 and 7 on the page.


Show your output from the exercises.

You might also like