DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Android Services

Android Services

Scott Mccain user avatar by
Scott Mccain
·
Oct. 04, 10 · Interview
Like (1)
Save
Tweet
Share
13.54K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

Android services stand apart from the typical Android application which includes an Activity and a rich user interaction.  Services on the Android platform utilize background processing and communicate to listeners by firing Intents, updating content providers, and/or triggering notifications.  The Activity that started the service can be inactive or even closed and the service will continue to run. 

A second form of an Android Service provides an interface to a remote object.  Both extend the Service class and override specific functions to provide the desired functionality.  This article will be covering the first form of a service.

Services normally can be stopped, started, and controlled from other applications.  These applications include other Services or Activities.  Services also receive higher priority than any inactive or invisible Activities.  This means your Service will be less likely to be prematurely stopped by the resource manager.

 

Create the Service

To create an Android Service you must create a class which extends android.app.Service.  To provide basic control and functionality you can override the onCreate(), onStart(), and onDestroy() methods.  You must also add the service to the application manifest file.  You can do that using the Eclipse ADT Plugin or by adding a Service block to the AndroidManifest.xml file.

Here is the skeleton sevice I will be fleshing out in this article:

package com.demo.service;

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

public class RSSService extends Service {

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

@Override
public void onCreate() {
super.onCreate();
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}

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

}

 

Here is the ApplicationManifest.xml entry for the example service in this article:

<service android:permission="android.permission.INTERNET" android:name=".RSSService" android:enabled="true"></service>

Simple UI

I will provide a simple UI for controlling the Service in this application.  Here is a screen shot of the UI:

 Simple UI

Here is the main.xml for the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="RSS Service Demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="Start"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:id="@+id/buttonStop"></Button>
</LinearLayout>

 

Let's look at how you stop and start a service before I show the UI code which controls the service:

// Start the RSSService
startService(new Intent(this, RSSService.class));

// Stop the RSSService
stopService(new Intent(this, RSSService.class))

 

Here is the UI code which utilizes that code: 

package com.demo.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button startButton = (Button) findViewById(R.id.buttonStart);
startButton.setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View arg0) {
Log.d("com.demo.service", "starting service.");

// Start the RSSService
startService(new Intent(MainActivity.this, RSSService.class));
}
});

Button stopButton = (Button) findViewById(R.id.buttonStop);
stopButton.setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
Log.d("com.demo.service", "stopping service.");

// Stop the RSSService
stopService(new Intent(MainActivity.this, RSSService.class)) }
});
}
}

 

RSS Service Code

Now let's look at our skeleton RSS Service.  I will be fleshing out this service in future articles.  For now this service is very simple and just responds to start and destroy controls. 

package com.demo.service;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

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

public class RSSService extends Service {

private Timer updateTimer;
private Date lastRead = new Date(1, 1, 1);

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

@Override
public void onCreate() {

updateTimer = new Timer("RSSServiceUpdateTimer");
}

@Override
public void onStart(Intent intent, int startId) {

Toast.makeText(this, "RSSService Startedd", Toast.LENGTH_LONG).show();

// TODO: Read from user preferences
int period = 10;

// cancel the current timer
updateTimer.cancel();

// create a new timer
updateTimer = new Timer("RSSServiceUpdateTimer");
updateTimer.scheduleAtFixedRate(
new TimerTask() {

@Override
public void run() {
RSSService.this.refreshFeed();
}

}, 0, period*60*1000);
}

protected void refreshFeed() {
// perform http lookup for new feeds
}

private void announceNewFeed(RSSMessage feed) {

}

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

Toast.makeText(this, "RSSService Stopped", Toast.LENGTH_LONG).show();
}

}

This is the main class for the Service and it is here where the onStart, onDestroy, and onCreate methods are implemented.  In this simple example we create an update timer in the onCreate method.  In the onStart method we set the update timer to auto fire at a specific interval.  This interval is hard coded for this example but a real application would provide a way for users to configure that setting.  When the timer fires we do the work.

Conclusion

Android Services are a powerful addition to the Android arsenal.  They give your application the ability to perform offline processing and/or notify multiple running applications of it's progress.  Services are an important citizen of the Android community so they are given priority when Android needs to clean up or free memory.  You can even expose objects via AIDL (Android Interface Definition Language) to consumers. 

Services are easy to understand once you peek under the complexity and see that they are basic background tasks that utilize all the same patterns we all know and love.

In the next installment I will show an example of how you can utilize this basic framework to create an RSS feed service for your applications.  In future articles I will show you how to create a rich UI to consume that feed as well.

 

Android (robot) application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Choosing the Right Framework for Your Project
  • Integrate AWS Secrets Manager in Spring Boot Application
  • How To Best Use Java Records as DTOs in Spring Boot 3
  • Java REST API Frameworks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: