Controlling a Service Android

At this point, the example code has a complete implementation of a Service. Now we write code to control the service we previously defined.

Intent service = new Intent(“com.androidbook.GPXService.SERVICE”);
service.putExtra(“update-rate”, 5000);
startService(service);

Starting a service is as straightforward as creating an Intent with the service name and calling the startService() method. In this example, we also set the update-rate Intent extra parameter to 5 seconds. That rate is quite frequent but works well for testing. For practical use, we probably want this set to 60 seconds or more. This code triggers a call to the onCreate() method, if the Service isn’t bound to or running already. It also triggers a call to the onStart() or onStartCommand() methods, even if the service is already running.

Later, when we finish with the service, it needs to be stopped using the following code:

Intent service = new Intent(“com.androidbook.GPXService.SERVICE”);
stopService(service);

This code is essentially the same as starting the service but with a call to the stopService() method.This calls the onDestroy() method if there are no bindings to it. However, if there are bindings, onDestroy() is not called until those are also terminated. This means background processing might continue despite a call to the stopService() method. If there is a need to control the background processing separate from these system calls, a remote interface is required.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Android Topics