Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Service Example for Background Processes

Android Service Example for Background Processes

December 30, 2016 by Belal Khan 17 Comments

Hey guys, in this post we will see a simple Android Service Example. But first lets understand what is an Android Service?

Contents

  • 1 What is Android Service?
  • 2 Android Service Example in Video
  • 3 Basics of an Android Service
    • 3.1 Creating a Service
    • 3.2 Defining it on Manifest
  • 4 Android Service Example
    • 4.1 Creating an Android Studio Project
    • 4.2 Creating User Interface
    • 4.3 Creating Service
    • 4.4 Defining Service in Manifest
    • 4.5 Starting and Stopping Service
    • 4.6 Sharing is Caring:
    • 4.7 Related

What is Android Service?

Service is a process, but the special thing is about the service is it doesn’t need user interaction and it runs on background. I hope you can imagine some Android Services Examples now. Like Playing music in background. It is a long running process and it does not need user interaction. In this Android Service Example I will show you playing music in background.

Android Service Example in Video

  • You can watch the following video to get a detailed explanation as well.

Basics of an Android Service

Creating a Service

To create service we will create a normal class extending the class Service. And we should override the following methods.

onStartCommand()

  • This method is invoked when the service is started using the startService() method. We can call the method startService() from any activity and it will request the service to start.

onBind()

  • If it is needed to bind the service with an activity this method is called. The service can result back something to the activity after binding. But if you do not want to bind the service with activity then you should 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.

Defining it on Manifest

  • You need to define your service in your AndroidManifest.xml file. It is very important.

1
<service android:name=".YourService" />

  • You need to put the above code inside application tag for every service.

Android Service Example

Now lets see a working Android Service Example.

Creating an Android Studio Project

  • Again create a new android studio project.

android service example

Creating User Interface

  • Once the project is loaded come inside activity_main.xml and create the following layout.

android service example

  • For the above UI you can use the following xml code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.simplifiedcoding.androidserviceexample.MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">
 
        <Button
            android:id="@+id/buttonStart"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Start Service" />
 
        <Button
            android:id="@+id/buttonStop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Stop Service" />
 
    </LinearLayout>
 
</RelativeLayout>

  • Now we will code the MainActivity.java as below.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package net.simplifiedcoding.androidserviceexample;
 
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.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);
 
        //attaching onclicklistener to buttons
        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
        }
    }
}

  • Now we will create our service.

Creating Service

  • To create a service you just need to create a new class extending Service. And also you need to override some methods.
  • I have create the following class MyService.java.

MyService.java
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package net.simplifiedcoding.androidserviceexample;
 
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
 
/**
* Created by Belal on 12/30/2016.
*/
 
public class MyService extends Service {
    //creating 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 systems default ringtone
        player = MediaPlayer.create(this,
                Settings.System.DEFAULT_RINGTONE_URI);
        //setting loop play to true
        //this will make the ringtone continuously playing
        player.setLooping(true);
 
        //staring the player
        player.start();
 
        //we have some options for service
        //start sticky means service will be explicity started and stopped
        return START_STICKY;
    }
 
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        //stopping the player when service is destroyed
        player.stop();
    }
}

  • As you can see we are simply playing the default ringtone inside the onStartCommand() so when you start this service the default ringtone will start ringing on loop until you don’t stop the service.

Defining Service in Manifest

  • Before starting the service we need to define it inside AndroidManifest.xml, so modify manifest file as below.

AndroidManifest.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.simplifiedcoding.androidserviceexample">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>
        
        <!-- defining the service class here -->
        <service android:name=".MyService" />
    </application>
 
</manifest>

  • Now lets see how we can start and stop the service.

Starting and Stopping Service

  • Again come inside MainActivity.java and modify it as below.

MainActivity.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package net.simplifiedcoding.androidserviceexample;
 
import android.content.Intent;
import android.media.MediaPlayer;
import android.provider.Settings;
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.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);
 
        //attaching onclicklistener to buttons
        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {
        if (view == buttonStart) {
            //starting service
            startService(new Intent(this, MyService.class));
        } else if (view == buttonStop) {
            //stopping service
            stopService(new Intent(this, MyService.class));
        }
    }
}

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

So thats all for this Android Service Example guys. Please leave out your comments if having any queries or confusions. Thank You 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Application Development, Android Intermediate Tagged With: android background service example, android service example, android services

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Mahendra says

    January 20, 2017 at 10:07 am

    in my oppo A33f after closing the app from recent app manager the service has stopped the playing ringtone

    Reply
    • Aman Sahai says

      December 4, 2017 at 7:05 am

      It is maybe because you have not used the onBind() to bind the service with the main activity.

      Reply
      • Aish says

        November 16, 2018 at 7:25 am

        How do we do that?

        Reply
  2. Vivek says

    March 3, 2017 at 11:31 am

    use this START_NOT_STICKY instead of START_STICKY in the MyService.java file to avoid restart of the music even after the app gets terminated completely

    Reply
  3. Debasmita Mishra says

    April 11, 2017 at 12:59 pm

    I am trying to set a countdown timer in recyclerview as an item, but that problem is when I am moving to other page this time is starting from first. How can I get update time, Can you please help me

    Reply
    • sandhiya says

      April 28, 2017 at 5:28 am

      I am aslo having same issue will u find the solution for this

      Reply
  4. Chandan Badtya says

    June 20, 2017 at 1:05 pm

    Thank you for this tutorial. I have been looking for this solution.. Very helpful

    Reply
  5. Ashfaq says

    August 9, 2017 at 5:17 am

    hi, I’m new to android development. will you please make a tutorial on how to send https GET request in the background (even if app closed) and show the data on notification or at least detailed example. I’m trying to do this for a while now, please?

    Reply
    • Belal Khan says

      August 9, 2017 at 5:51 pm

      You have to make a service that will keep running in background..

      Reply
  6. alami says

    August 14, 2017 at 1:16 pm

    Please how can start music in launching application without pressing start

    Reply
  7. Dinu says

    November 18, 2017 at 7:15 am

    Thank you . Its working

    One more Doubt :

    How to check internet connection through service.
    Eg : WiFi or Mobile Data is Connected but No Internet at present at the time or manage speed of the internet.

    Reply
  8. Jerome says

    December 14, 2017 at 5:05 pm

    Hi, thanks for the explanation.

    My question is why the app keeps stopping when the start button is pressed? (the music is playing ok)

    Thanks again.

    Reply
  9. Krishna says

    February 1, 2018 at 7:35 pm

    Working fine ! but when i close the app from RECENT APPS it will going stop sound. How do i resolve this ?
    I’am using android nougat version.
    Thanks.

    Reply
  10. Ranjith Ganesan says

    May 18, 2018 at 11:52 am

    Explain about START_NOT_STICKY and START_STICKY

    Reply
  11. Zain Ali says

    August 3, 2018 at 11:18 am

    Thanks a lot for making this tutorial.
    Thanks again.
    Thanks again.

    Thanks 100 times.
    Happy Coding 🙂

    Reply
  12. tabby says

    August 10, 2018 at 6:17 am

    every 10mint later service will stop and then after 10 mint service should start automatically how could do that ?

    Reply
  13. Pravinsingh Waghela says

    October 28, 2018 at 1:09 pm

    In Oreo startService is Depricated. So Can you Please provide the workaround for Oreo with the same example.

    Reply

Leave a Reply to Chandan Badtya Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.