Android Services
Join the DZone community and get the full member experience.
Join For FreeIntroduction
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:
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.
Opinions expressed by DZone contributors are their own.
Comments