Presentation is loading. Please wait.

Presentation is loading. Please wait.

Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.

Similar presentations


Presentation on theme: "Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android."— Presentation transcript:

1 Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android runs in background, they don’t have an interface and have a life-cycle very different from Activities. Using Service we can implement some background operation Examples Network Downloads Playing Music in the background while the user is in a different application TCP/UDP Server You can bind to a an existing service and control its operation fetch data over the network without blocking user interaction with an activity

2 Service state forms A service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform inter-process communication (IPC). A service can essentially take two forms: Started 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. Bound 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 inter-process communication (IPC).

3 Life of Cycle context.startService() ->onCreate()->onStart()->Service running--->context.stopService() - >onDestroy() context.bindService()->onCreate()->onBind()->Service running--->onUnbind() -> onDestroy() To create a service, you must create a subclass of Service(or one of its existing subclass). onStartCommand(): The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). onBind(): The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). onCreate() The system calls this method when the service is first created, to perform one-time setup procedures onDestroy() The system calls this method when the service is no longer used and is being destroyed.

4 Services has different life cycle from Activity. Services has different method for their life cycle which is startService(), stopService(), onBindService()

5 Difference between bound and unbound service in Android Android Bound Service and Unbound Service run in Background Android Services is used to do any background task in current activity. Bound Service: Service which call indefinitely in between activity 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. Unbound Service: Service which call at the life span of calling activity 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.

6 The difference between them If a component starts the service by calling startService() (which results in a call to onStartCommand()), then the service remains running until it stops itself with stopSelf() or another component stops it by calling stopService(). If a component calls bindService() to create the service (and onStartCommand is not called), then the service runs only as long as the component is bound to it. Once the service is unbound from all clients, the system destroys it.

7 Android Activity can be started, stopped, destroyed if the system resources become too low and maybe can be recreated, a Service are designed to have a longer life. A Service in Android can be started from an Activity, from a Broadcast receiver and other services too. We have to notice that using Service we don’t create automatically new threads, so if we implement a simple logic inside our Service, that doesn’t require long time processing we don’t need to run it a separate thread, but if we have to implement complex logic, with long time processing, we have to take care of creating a new thread, otherwise the service runs on the main thread and it could cause ANR problem.

8 Service applications *Implement multi-task *Enable Inter-Process-Communication (IPC) A typical example of the first case is an app that required to download data from a remote server, in this case we can have Activity that interacts with a user and starts a service that accomplishes the work in background while the user can use the app and maybe when the service finishes sends a message to the user. In the second case, we want to “share” some common functions so that different app can re-use them. For example, we can suppose we have a service that sends an email and we want to share this service among several apps so that we don’t have to rewrite the same code. In this case we can use IPC so that the service exposes a “remote” interface that can be called by other app

9 Service basics In Android to create a Service we have to extend Service class public class TestService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } In this case, only implement only one method called onBind using local service, so this method should return null.

10 Service lifecycle and override its callback methods public class TestService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { return null; }

11 onCreate and OnStartCommand The first method onCreate is called only one time when the Service has to created. If the Service is already running this method won’t be called. We don’t call it directly but it is the OS that calls it. We can notice that the onCreate method is called because it is the first time we start the service, if we click again on start button the OS doesn’t call onCreate method. When we click on stop button the OS destroy the service. OnStartCommand is is called when we required to start the Service. In this method we have the Intent passed at time we run the Service, in this way we can exchange some information with the Service. In this method, we implement our logic that can be execute directly inside this method if it isn’t time expensive otherwise we can create a thread. As you can see this method requires we return an Integer as result. This integer represents how the Service should be handled by the OS: START_STICKY : Using this return value, if the OS kills our Service it will recreate it but the Intent that was sent to the Service isn’t redelivered. In this way the Service is always running START_NOT_STICKY: If the SO kills the Service it won’t recreate it until the client calls explicitly onStart command START_REDELIVER_INTENT: It is similar to the START_STICKY and in this case the Intent will be redelivered to the service.

12 Service declaration in Manifest.xml declare service in the Manifest.xml so that we can use it: <service android:name=".TestService" android:enabled="true"/> Start and Stop Service As we know a Service has to be started and eventually stopped so that it can accomplish its task. We can suppose to start it from an activity and we could pass to the service some information using Intent. We can suppose that our Activity has two buttons one to start and one to stop the Service:

13 @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, TestService.class); i.putExtra("name", "SurvivingwithAndroid"); MainActivity.this.startService(i); } }); btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, TestService.class); MainActivity.this.stopService(i); } }); In the code above at line 5, we create an Intent passing the class name that handles our Service, moreover we set some params like name and then we start the Service at line 7. In the same way, at line 17 we stop the service

14 Clicking on Start button we get in the Log:

15 Starting service automatically Many times we want to start our service automatically, for example at boot time. We know to start a Service we need a component to start it. How can we do it? Well, we could use a Broadcast receiver that starts our service. If for example we want to start it at the smartphone boot time, we create first a Broadcast receiver that listens to this event and then it starts the service. public class BootBroadcast extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { ctx.startService(new Intent(ctx, TestService.class)); } and in the Manifest.xml

16 Service description: A service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform inter-process communication (IPC). A service can essentially take two forms: Started 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. Bound 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 inter-process communication (IPC).


Download ppt "Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android."

Similar presentations


Ads by Google