Click here to Skip to main content
15,890,438 members
Articles / Mobile Apps / Android
Tip/Trick

How to Develop a Simple Android Service

Rate me:
Please Sign up or sign in to vote.
4.55/5 (7 votes)
9 Mar 2015CPOL2 min read 25.9K   979   27  
Simple way to create service on Android Application

Introduction

Do you want a mobile app which can do some tasks such as playing music, downloading file while you are viewing the news or chatting? This kind of application is called by "Service". It can run in the background and not affect to your current operation.

This tip will show you how to develop a simple service application on Android Platform.

This application allows user to start and stop a background service. This service displays the Toast Message when starting or stopping.

Background

Image 1

A service is one of the Android components which runs in the background. It doesn't run on main UI thread so it doesn't have direct interaction with the user.

Service has no UI and does not affect the activity lifecyle. It runs in the background thread of the application to perform long running or repeative operations such as internet download, playing music, monitoring the data, etc.

As in the above figure, an application component such as activity, fragment call method Start service to start the service. After it is called, a service runs in the background even if the component that started it is destroyed. It only stops when the application calls the stop service.

Using the Code

Open Eclipse, create an Android Application Project as normal. In this tip, I create an Android 5.0.1 project. The default package is com.example.servicedemo.

In AndroidManifest.xml file, declare the Android Service.

XML
<service
           android:name="com.example.servicedemo.DemoService"
           android:label="@string/service_demo" >
</service>

Note that you have to declare the full name and path of your service to prevent the exception when launching the app.

"com.example.service.demo" is a package name. DemoService is service name.

Create a new Java class name "DemoService".

<p<img height="257px" src="/KB/android/884235/Snap_2015-03-09_at_15.50.00.png" width="389px">

Implement this class as Service by extending to Service class.

Java
package com.example.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class DemoService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

In the above code block, the Service is default Android Service class.

Now, we start to design a simple GUI of this app. To design GUI, you can use the Built-in Layout design tool or code by XML. In this article, I prefer the XML code.

Open the strings.xml file, define some string constants for this app.

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

    <string name="app_name">ServiceDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="service_demo">Service Demo</string>
    <string name="start_service">Start Service</string>
    <string name="stop_service">Stop Service</string>

</resources>

Open the activity_main.xml file, enter the following code.

XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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="com.example.servicedemo.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="144dp"
        android:text="@string/service_demo"
        android:textColor="#000"
        android:textSize="20sp" />

    <Button
        android:id="@+id/btn_start_service"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="28dp"
        android:text="@string/start_service" />

    <Button
        android:id="@+id/btn_stop_service"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/btn_start_service"
        android:layout_below="@+id/btn_start_service"
        android:layout_marginTop="42dp"
        android:text="@string/stop_service" />

</RelativeLayout>

In this code, we create a relative layout and add 2 buttons named "Start Service" and "Stop Service" to do the corresponding action. The GUI layout will be displayed like this in GraphicLayout tab.

Image 2

In MainActivity, implement the following code:

Java
package com.example.servicedemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity implements OnClickListener {
    Button mStartService;
    Button mStopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Declare the start service button
        mStartService = (Button) findViewById(R.id.btn_start_service);

        // Declare the stop service button
        mStopService = (Button) findViewById(R.id.btn_stop_service);

        // Add event listener to each button
        mStartService.setOnClickListener(this);
        mStopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        // User click start button
        if (v.getId() == R.id.btn_start_service) {
            // Display the Toast Message
            startService(new Intent(getBaseContext(), DemoService.class));
        } else { // User click stop button

            // Stop the service
            stopService(new Intent(getBaseContext(), DemoService.class));
        }
    }
}

Open the DemoService.java, enter the following code:

Java
package com.example.servicedemo;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class DemoService extends Service {

    private static final String TAG = "DemoService";
    private final int INTERVAL = 60 * 1000;
    private Timer timer = new Timer();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onCreate() Called by the system when the service
     * is first created. Do not call this method directly.
     */
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "Service is created", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        // Display the Toast Message
        Toast.makeText(this, "Start Service", Toast.LENGTH_SHORT).show();

        // Execute an action after period time
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                // Print a log
                Log.d(TAG, "Start to do an action");
            }
        }, 0, INTERVAL);
        return super.onStartCommand(intent, flags, startId);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Service#onDestroy() Service is destroyed when user stop
     * the service
     */
    @Override
    public void onDestroy() {
        // Display the Toast Message
        Toast.makeText(this, "Stop Service", Toast.LENGTH_SHORT).show();
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
    }
}

In the above code, when service is started, it will repeat running an action (Print the log) after period time INTERVAL (Milliseconds). You can change this action to whatever you want such as play music, downloading file, etc.

When user presses the Stop button to stop service, the service is destroyed in method onDestroy, you can stop the current action here. In this code, the timer is canceled to stop printing the log on Logcat.

History

This is the initial version of this tip.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Panasonic
Vietnam Vietnam
I am a technical engineer with 7 years experience in both software and hardware. I have been working for Panasonic Corp for 4 years.

"Work smart than work hard" is my motto. I like working with excellent people throughout the world. I have a focus on quality and am diligent about meeting deadlines.

Comments and Discussions

 
-- There are no messages in this forum --