Sie sind auf Seite 1von 7

What are Services in Android System?

1) Faceless components: The components of Android system that run in the background are
Service components. They are very much like activities, only without a User Interface.
2) Taking care of long running background tasks: They carry out long-running tasks desired by
the application (without user intervention). Services run the background tasks that do not require a
User Interface.
3) Unaffected by activity switching: Each Service has a specific job, and they keep at it if you
switch between different Activities, or even if you switch to a different application altogether.
4) It can also provide functionality to other applications.
5) Example of Service: A good example is your music player.
When you play music in your Android handset using a playlist, the music player takes care of the job
itself, without user intervention. You do not have to change the song every time one song ends. This
automation is due to the service component of Android.
We have discussed the music player example in in the end. Keep reading for it to make sense! :)

Service Lifecycle
Let us now discuss the Service life-cycle. Because a Service lacks a user interface, it always runs in
the background (unlike an activity). As a result, its life stages vary a bit from Activitys life-cycle.
You would remember that an activity is in a paused state when it is visible but the user is not
interacting with it.
As a Service always runs in the background no matter which activity the user is interacting with,
Paused State is not a possibility.
Therefore, a Service has the following stages:

Starting
Running
Destroyed

1
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

Definition :
A service is a component that runs in the background to perform long-running operations without
needing to interact with the user. For example, a service might play music in the background while
the user is in a different application, or it might fetch data over the network without blocking user
interaction with an activity. A service can essentially take two states:
State
Started

Bound

Description
A service is started when an application component, such as an activity, starts it
by calling startService(). Once started, a service can run in the background
indefinitely, even if the component that started it is destroyed.
A service is bound when an application component binds to it by calling
bindService(). A bound service offers a client-server interface that allows
components to interact with the service, send requests, get results, and even do
so across processes with interprocess communication (IPC).

A service has lifecycle callback methods that you can implement to monitor changes in the service's
state and you can perform work at the appropriate stage. The following diagram on the left shows the
lifecycle when the service is created with startService() and the diagram on the right shows the
lifecycle when the service is created with bindService(): (image courtesy : android.com )

2
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

To create an service, you create a Java class that extends the Service base class or one of its existing
subclasses. The Service base class defines various callback methods and the most important are
given below. You don't need to implement all the callbacks methods. However, it's important that
you understand each one and implement those that ensure your app behaves the way users expect.
Callback

Description
The system calls this method when another component, such as an activity,
requests that the service be started, by calling startService(). If you implement
onStartCommand()
this method, it is your responsibility to stop the service when its work is done,
by calling stopSelf() or stopService() methods.
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must
onBind()
provide an interface that clients use to communicate with the service, by
returning an IBinder object. You must always implement this method, but if
you don't want to allow binding, then you should return null.
The system calls this method when all clients have disconnected from a
onUnbind()
particular interface published by the service.
The system calls this method when new clients have connected to the service,
onRebind()
after it had previously been notified that all had disconnected in its
onUnbind(Intent).
The system calls this method when the service is first created using
onCreate()
onStartCommand() or onBind(). This call is required to perform one-time setup.
onDestroy()
The system calls this method when the service is no longer used and is being
3
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

destroyed. Your service should implement this to clean up any resources such
as threads, registered listeners, receivers, etc.

Forms of Service
A Service can have two forms:
1) Started/Unbound: In this case, an application component starts the service, and it would
continue to run in the background, even if the original component that initiated it is destroyed.
For instance, when started, a service would continue to play music in the background indefinitely.
2) Bound: An Android component may bind itself to a Service using bindservice (). A bound service
would run as long as the other application components are bound to it. As soon as they unbind,
the service destroys itself.
An unbound activity runs indefinitely, whereas the lifespan of a bound activity depends on the
application components that bind to it.

When are the Services running in the background destroyed?


Even though (by definition) services should carry out long running operations indefinitely, they are
fated to be eventually killed by the Android system, if they run in the background.
This is how it happens:

1) When a Service starts, it runs in the main process:


A service when created does not create a separate thread/process for itself (unless instructed to do
so); instead, it runs in the main thread of the running application, thus consuming the memory
resources of the main system.

2) What happens in case of low system memory?


The system would choose to close the components that are low priority, but are still consuming the
system resources. Thus, the background components not in user focus are the first ones the
system kills. Therefore, it would destroy the services running in the background. This is to free
system resources for more important components (Example: for the activity in the foreground
interacting with the user).

3) Does system follow a pattern while killing services to free resources?


Yes it does! Read on to find out:
a) Unbound Service: Over time, the system pushes down a long-running service to lower priority in
the list of background tasks, and this service is more likely to close first (if unbound), when memory
shortage occurs.
b) Services bound to foreground activity: The services that are bound to an activity or any other
application component running in the foreground are less likely to be killed than an unbound activity.
4
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

c) Foreground Services: The system would never kill a service if it were declared to run in the
foreground. We would discuss more about this in later Android tutorials. Stay put!

4) How to keep a Service from being killed?


a) You can create separate threads while creating services for the services to run. Thus, there is
reduced consumption of main application memory, and the likelihood of the service being destroyed
due to memory shortage is lower than otherwise.
b) As discussed before, you can declare a Service to run in the foreground. This can prevent the
system from killing the Service.

Services Example
We have used the most basic example of a Service, i.e. Music Player.
Here are the code and snapshots for playing and stopping a song using a Service:
Follow the steps described in this Android Tutorial:
Step 1: Create a new Android Project with the class name MainActivity.
Step 2: Add two buttons in layout and name them as play and stop.
Step 3: Set the onClick Listeners of both buttons inside the MainActivity.
Step 4: Create a new class MyService and extends it to Service Class
Step 5: Make a new folder named as raw inside the res directory, and copy a song inside it.
Tag to add in Manifest:
<service
android:name=.MyService
android:enabled=true >
</service>

Code : MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
5
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

Button play, stop;


play = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service = new Intent(MainActivity.this, MyService.class);
startService(service);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent name = new Intent(MainActivity.this, MyService.class);
stopService(name);
}
});
}
}

Code: MyService.java
public class MyService extends Service {
MediaPlayer mp;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
6
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

@Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(getApplicationContext(), R.raw.song);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp.start();
return 0;
}
@Override
public void onDestroy() {
mp.release();
super.onDestroy();
}
}

7
Resource Provider : (Muhammad Rizwan) Visiting Lecturer, IUB-RYK

Das könnte Ihnen auch gefallen