Services are software components designed specifically to perform long background operations.

Similar documents
MOBILE APPLICATION DEVELOPMENT LECTURE 10 SERVICES IMRAN IHSAN ASSISTANT PROFESSOR

Android Fundamentals - Part 1

Services. Background operating component without a visual interface Running in the background indefinitely

Software Practice 3 Today s lecture Today s Task

CS378 -Mobile Computing. Services and Broadcast Receivers

EMBEDDED SYSTEMS PROGRAMMING Android Services

ANDROID SERVICES, BROADCAST RECEIVER, APPLICATION RESOURCES AND PROCESS

Android. Broadcasts Services Notifications

Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5

Services. Marco Ronchetti Università degli Studi di Trento

Lecture 2 Android SDK

Android Services & Local IPC: The Command Processor Pattern (Part 1)

Mobile Application Development Android

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Mobile Application Development Android

Android System Development Day-4. Team Emertxe

Minds-on: Android. Session 2

Services. Marco Ronchetti Università degli Studi di Trento

Application Fundamentals

Android Services & Local IPC: Overview of Programming Bound Services

Services Broadcast Receivers Permissions

Programming with Android: Notifications, Threads, Services. Luca Bedogni. Dipartimento di Scienze dell Informazione Università di Bologna

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL II)

Mobile Application Development Android

Services & Interprocess Communication (IPC) CS 282 Principles of Operating Systems II Systems Programming for Android

Mobile Computing. Introduction to Android

Programming in Android. Nick Bopp

1. GOALS and MOTIVATION

Services. service: A background task used by an app.

Security Philosophy. Humans have difficulty understanding risk

App Development for Android. Prabhaker Matet

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle

Android Ecosystem and. Revised v4presenter. What s New

Implementing a Download Background Service

Understanding Application

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

Android Services. Victor Matos Cleveland State University. Services

ios vs Android By: Group 2

CS378 -Mobile Computing. Audio

Broadcast receivers. Marco Ronchetti Università degli Studi di Trento

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu

Android Services & Local IPC: The Activator Pattern (Part 2)

Lecture 3 Android Internals

Security model. Marco Ronchetti Università degli Studi di Trento

Introduction to Android

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

application components

Efficient Android Threading

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Lab 5 Periodic Task Scheduling

MC Android Programming

Multiple Activities. Many apps have multiple activities

android application development CONTENTS 1.1 INTRODUCTION TO O ANDROID OPERATING SYSTEM... TURES Understanding the Android Software Stack...

Operating Systems. Review ENCE 360

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Android framework. How to use it and extend it

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

COLLEGE OF ENGINEERING, NASHIK-4

SMD149 - Operating Systems

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

Termite WiFi Direct API

Android Programming (5 Days)

Notifications and Services. Landon Cox March 28, 2017

Android OA Android Application Engineer(R) Certifications Basic.

App Development for Smart Devices. Lec #7: Windows Azure

Programming Android UI. J. Serrat Software Design December 2017

Midterm Examination. CSCE 4623 (Fall 2017) October 20, 2017

Android Basics. Android UI Architecture. Android UI 1

Android Application Development

COSC 3P97 Mobile Computing

CHAPTER 3 - PROCESS CONCEPT

2017 Pearson Educa2on, Inc., Hoboken, NJ. All rights reserved.

CSCU9YH Development with Android

Android Activities. Akhilesh Tyagi

EMBEDDED SYSTEMS PROGRAMMING Application Basics

Processes Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.

Learning Outcomes. Processes and Threads. Major Requirements of an Operating System. Processes and Threads

Processes, PCB, Context Switch

Announcements. Program #1. Reading. Due 2/15 at 5:00 pm. Finish scheduling Process Synchronization: Chapter 6 (8 th Ed) or Chapter 7 (6 th Ed)

CS Android. Vitaly Shmatikov

Syllabus- Java + Android. Java Fundamentals

Implementation of Processes

32. And this is an example on how to retrieve the messages received through NFC.

Android Architecture and Binder. Dhinakaran Pandiyan Saketh Paranjape

Lecture 1 - Introduction to Android

Lifecycle-Aware Components Live Data ViewModel Room Library

CMSC436: Fall 2013 Week 3 Lab

UNDERSTANDING ACTIVITIES

1 System & Activities

Processes and Threads

MODELS OF DISTRIBUTED SYSTEMS

Lecture 4: Memory Management & The Programming Interface

Why using intents. Activity. Screen1 Screen 2

CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu

Android Software Development Kit (Part I)

Chapter 4: Threads. Operating System Concepts 9 th Edition

Introduction to Android

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies

ANDROID DEVELOPMENT. Course Details

Transcription:

SERVICES

Service Services are software components designed specifically to perform long background operations. such as downloading a file over an internet connection or streaming music to the user, but do not require a user interface. Services have a lifecycle that is separate from that of the component, such as an Activity, that starts them. This autonomy allows a service to continue running even after the starting component is no longer alive.

Service type Started Service Something to be done in the background. It doesn t provide a result (although it can send a broadcast or set a notification) Started with context.startservice(intent) onbind() must return null Bound Service Allows a client to set up a connection (bind) with the service so that methods can be called Started with context.bindservice(intent,serviceconnetcion,flags) onbind() returns an interface with methods that can be called

Service lifecycle

Starting the Service The service to be started is identified via an intent, provided as an argument of StartService(..) and bindservice(..) Explicit intent are recommended What about implicit intents? What happen if two services respond to the same action? The system selects one service at random (!) Given a higher priority can force the selection Priority is a field of the <intent-filter> tag

Service class java.lang.object android.content.context android.content.broadcastreceiver android.content.contextwrapper android.app.service android.content.contextthemewrapper android.app.intentservice android.app.activity

Intent service The IntentService class is a convenience class (subclassed from the Service class) that sets up a worker thread for handling background tasks and handles each request in an FIFO order. Once the service has handled all queued requests, it simply exits. All that is required when using the IntentService class is to implement onhandleintent(intent) method

Intent Service: example Main Activity Explicit Intent Intent Service The service needs to be registered in the manifest file The main activity creates an explicit intent pointing to the service The service is started and the onhandleintent method executed Intents are queued and served serially

Intent Service (demo)

Example Suppose we want to sync with a local content provider with a server, but only when an internet connection is available. This is one possible solution: Register a broadcast receiver to the following bcast intent: ConnectionManager.CONNECTIVITY_ACTION (When the connectivity changes this intent is fired) Check (from the receiver) if now the connection is now up If this is the case, then start an IntentService The IntentService will use a Socket to open a stream with the server Data are read from the content provider

Solution (sync) Socket Intent Service Start Broadcast Receiver ContentProvider ConnectivityManager.CONNECTIVITY_ACTION

Another example Check a condition every minute..(warning: registration must be dynamic, i.e. from inside an activity) Activity B Activity A register receiver Notification Manager Create a PendingIntent Intent Service Start Broadcast Receiver Time tick

Another example (do something periodically) Activity Activity Notification Manager Intent Service PendingIntent Create a pending intent Set a periodic alarm Alarm Manager

Another example (do something periodically). Solution 2 Activity Activity Notification Manager Intent Service Create a pending intent Set an alarm PendingIntent Create a p.i, Set an alarm Alarm Manager

Started service Started services are launched by other application components (such as an activity or even a broadcast receiver) and potentially run indefinitely in the background until the service is stopped, or is destroyed by the Android runtime system in order to free up resources. A service will continue to run if the application that started it is no longer in the foreground, and even in the event that the component that originally started the service is destroyed. By default, a service will run within the same main thread as the application process from which it was launched (referred to as a local service). It is important, therefore, that any CPU intensive tasks be performed in a new thread within the service

Started service Unless a service is specifically configured to be private (once again via a setting in the manifest file), that service can be started by other components on the same Android device. This is achieved using the Intent mechanism in the same way that one activity can launch another as outlined in preceding slides. Started services are launched via a call to the startservice() method, passing through as an argument an Intent object identifying the service to be started. When a started service has completed its tasks, it should stop itself via a call to stopself(). Alternatively, a running service may be stopped by another component via a call to the stopservice() method, passing through as an argument the matching Intent for the service to be stopped. Services are given a high priority by the Android system and are typically amongst the last to be terminated in order to free up resource

Example Let s suppose we want run music in background We can use the MediaPlayer class to play, for example, an.mp3 file stored in the raw directory The MediaPlayer has the create(context,id) method that creates an istance of the MediaPlayer (say player) for the specified resource id A simple application will have two buttons (start and stop) The start button will call the start method on the player The stop button will call the stop method on the player

Example Activity A This solution is wrong Why? oncreate: player=mediaplayer(ctx,r.raw.song) startbutton: player.start() startbutton: player.stop() Suppose the user kills the activity And then starts the activity again. If it clicks the start button a new instance of the song is started Even worst the stop buttons doesn t Stop the previous song

Solution with started service Main Thread Play thread Process Service UI Activity An application that runs a player to play a song The service is started from the Activity and then it spawns a thread

Solution with started service startservice(intent) onstartcommand( ) Activity is killed X Activity is created startservice(intent) onstartcommand( ) A simple flag avoids to call another instance of MediaPlayer stopservice(intent) ondestroy()

Design guides OnCreate Called one time when the service is first started. This is where initialization code should be implemented. OnStartCommand Called for each request to start the service, either as a result of a call to StartService or a restart by the system. The method returns a StartCommmandResult value that indicates how or if the system should handle restarting the service after a shutdown due to low memory. This call takes place on the main thread. OnDestroy Called after the service receives a StopSelf or StopService call. This is where service-wide cleanup can be performed.

StartCommmandResult code Sticky A sticky service will be restarted, and a null intent will be delivered to OnStartCommand at restart. Redeliver Intent The service is restarted, and the last intent that was delivered to OnStartCommand before the service was stopped by the system is redelivered. Not Sticky The service is not automatically restarted.

Foreground service By default services are background, meaning that if the system needs to kill them to reclaim more memory, they can be killed without too much harm. The method startforeground(id,notification) Makes a service run in the foreground state (meaning is less likely to be killed by the OS), supplying the ongoing notification to be shown to the user while in this state. For example in the background music playback, the user would notice if the music stopped playing. Application can also acquire a wake-lock (avoids the CPU to go in the idle state) and a wifi-lock (to avoid turning the radio off if streaming is done from internet)

Bound Service (concept) A bound service is similar to a started service with the exception that it permits interaction with the component that launched it. With a started service this could be partially achieved setting a specific key in the intent to indicate some action to be performed (like, start the song again) However, a bound service allows the launching component to interact with, and receive results from, the service. Through the implementation of interprocess communication (IPC), this interaction can also take place across process boundaries.

Bound Service (clients) A component starts and binds to a bound service via a call to the bindservice(intent,serviceconnection,flag) method Intent: identifies the service ServiceConnection is an interface with two callback methods (called when the connection to the service is established or lost) Operation options for the binding (may be 0). See documentation Multiple components may bind to a service simultaneously. A component unbinds the service calling unbindservice(serviceconnection) ServiceConnection is the same one used to bind When the last bound client unbinds from a service, the service will be terminated by the Android runtime system.

Bound Service (clients) A bound Service is not a correct solution for playing music in background. Why? Hint: same problem as for the first solution (activity) However, a bound service may also be started via call to startservice( ) Once started, components may then bind to it via bindservice(..) calls When a bound service is launched via a call to startservice(..) it will continue to run even after the last client unbinds from it

Bound Service (server) A bound service extends the Servive class It must include an implementation of the onbind() that returns an object that implements IBinder (which is an interface). The object must extend the Binder class (that implements IBinder) A bound service can be local (belonging to the same package and running in the same process) or remote. In the case of local service the implementation is easier For remote service interprocess communication requires proxy and skeleton, plus the aild tool (see official documentation).

Bound Service (local service) A service can be bounded to another SW component, meaning that it can invoke methods implemented by the service through a proxy (Binder) of the Service (which is seen as a remote object) ServiceConnection is an interface monitoring connections to a service ServiceConnection <<interface>> Activity 1. bindservice() 2. onbind() returns a reference through which calling methods Service

Remote services It is possible to access a service running in a different process IDL aidl tool generates proxy skelethon process A process B

Service vs Thread A service is a component that Android is aware of (it must be declared in the manifest), with its own lifecycle A service can be activated from other components (not true for threads) A service is destroyed by the system only under very heavy circumstances and re-created according to restart options A service is in a sense similar to a Unix s daemon, e.g, it can be used system-wide and started automatically after the device boot ends

Service process priority The system kills the process hosting a service if it is under heavy memory pressure. However, if this happens, the system will later try to restart the service (and a pending intent can be delivered again) A processes hosting service have higher priority than those running an activity

System Services Lots of useful services See documentation