Now that we
have worked with services and notifications separately, we are all ready to use
the two together to make a real service that is notified to the user through a
status bar update that the service is running. The status bar removes the
notification as soon as the service is stopped.
In this
program, I also increment a counter once the service starts to show that the
service is continuously running in the background while we do other work. When
we stop the service we are able to see the updated count.
Let us look at
the code:
I have created
a class NotifyService which extends the service
class. This is the service class that will be started through the activity – ServiceLauncher
Now let us see what the service does?
It does 3 things – Toast a message that the service has
started. Update the status bar with a notification. Finally start incrementing
the counter. All this is done in the onCreate() method of
the NotifyService Class
Toast.makeText(this,"Service
created at " + time.getTime(), Toast.LENGTH_LONG).show();
showNotification();
incrementCounter();
Here is the
showNotification() Method:
private void showNotification()
{
CharSequence text = getText(R.string.service_started);
Notification notification = new Notification(R.drawable.android, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, ServiceLauncher.class), 0);
notification.setLatestEventInfo(this, getText(R.string.service_label),
text, contentIntent);
nm.notify(R.string.service_started, notification);
}
Finally, here
is the method for incrementing the counter incrementCounter():
private void incrementCounter()
{
timer.scheduleAtFixedRate(new TimerTask(){ public void run() {counter++;}}, 0, 1000L);
}
On stopping the
service, it obviously has to do the reverse actions: stop the counter, remove
the status bar notification and then toast a message to the end user saying the
service has stopped! So here it is:
shutdownCounter();
nm.cancel(R.string.service_started);
Toast.makeText(this, "Service
destroyed at " + time.getTime() + "; counter is at: " + counter, Toast.LENGTH_LONG).show();
counter=null;
This is the
code in the onDestroy()
method in the NotifyService
class.
With this the
service is ready. But we need to be able to start this service and stop it.
This I have done through a ServiceLauncher class just as I had done in the
previous part of this series. You can get the complete code here.