SlideShare ist ein Scribd-Unternehmen logo
1 von 60
Downloaden Sie, um offline zu lesen
Team Emertxe
Android System Development
Day-4
Android System Service
● Introduction to service
● Inter Process Communication (IPC)
● Adding Custom Service
● Writing Custom HAL
● Compiling SDK
● Testing Custom Service
Table of Content
Introduction to service
“A Service is an application component that can
perform long-running operations in the background and
does not provide a user interface”
“A Service is an application component that can
perform long-running operations in the background and
does not provide a user interface”
● Another app 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)
● Example - play music, download a file, tracking distance
traveled through sensor, all from the background
Introduction to Service
(what?)
Introduction to Service
(what?)
● Service is not process
● Faceless task that runs in the background
● No visual user interface
● Can run indefinitely unless stopped
● Each service extends the Service base class
Introduction to Service
(Types)
● Scheduled
● Started
● Bound
Introduction to Service
(Types - Scheduled)
● A service is scheduled through JobScheduler
● JobScheduler API was introduced in Android 5.0
(API level 21)
● API is used for scheduling various types of jobs
against the framework that will be executed in
app’s own process
● Example :
– Cricket score update
Introduction to Service
(Types - Started)
● A service is started when an application component
(such as an activity) calls startService()
● After it's started, a service can run in background
indefinitely, even if the component that started it is
destroyed
● Usually, a started service performs a single operation
and does not return a result to the caller
● Example : download or upload a file over the network
● When operation is complete, service should stop itself
Introduction to Service
(Types - Bound)
“A bound service is the server in a client-server
interface. It allows components (such as activities) to
bind to the service, send requests, receive responses,
and perform interprocess communication (IPC)”
“A bound service is the server in a client-server
interface. It allows components (such as activities) to
bind to the service, send requests, receive responses,
and perform interprocess communication (IPC)”
● A bound service typically lives only while it serves another app
component and does not run in the background indefinitely
● Example : GPS service
Introduction to Service
(Types - Bound)
● A service is bound when an app component
binds to it by calling bindService()
● A bound service runs only as long as another
app component is bound to it
● Multiple components can bind to the service at
once, but when all of them unbind, the service
is destroyed
Introduction to Service
(Basics)
● A service can be started (to run indefinitely),
bound or both
● Any app component can use the service (even
from a separate application) in the same way
that any component can use an activity—by
starting it with an Intent
● If required, declare the service as private in
manifest file and block access from other app
Introduction to Service
(Basics)
● A service runs in the main thread of its hosting
process
● The service does not create its own thread and does
not run in a separate process unless specified
Services expected to do CPU-intensive work or blocking
operations, such as MP3 playback or networking, shall
create a new thread within the service to complete that
work
Separate thread reduces the risk of “Application Not
Responding” (ANR) errors, and apps main thread can
remain dedicated to user interaction with activities
Introduction to Service
(Life-cycle)
Inter-Process Communication
IPC
(Different ways)
● AIDL
● Binder
● Message
IPC
(AIDL)
“Android Interface Definition Language (AIDL) enables
to define programming interface that both client and
service agree upon in order to communicate with each
other using inter-process communication (IPC)”
“Android Interface Definition Language (AIDL) enables
to define programming interface that both client and
service agree upon in order to communicate with each
other using inter-process communication (IPC)”
IPC
(AIDL)
AIDL usage is necessary only if you allow
clients from different applications to access
your service for IPC and want to handle multi-
threading in your service
AIDL usage is necessary only if you allow
clients from different applications to access
your service for IPC and want to handle multi-
threading in your service
Example : A sensor hub service catering
to different requests from multiple apps
IPC
(AIDL - why?)
● In Android, one process cannot normally access
the memory of another process
● So processes need to decompose their objects into
primitives that operating system can understand
● These primitives are marshalled by OS across
process boundary
● The marshalling code is tedious to write, so
Android handles it with AIDL
AIDL
(usage)
App1 App2 App3 . . .
Service
AIDL
IPC
(Binder)
● Create your interface by extending Binder if -
– There is no need to perform concurrent IPC across
different apps
– Your service is private to your own application and
runs in the same process as the client (your service
is merely a background worker for your own app)
IPC
(Binder - usage)
App Component A
Service
App Component B
App
IPC
(Binder - class)
● Binder is base class for a remotable object
● Binder class implements IBinder interface
● IBinder provides standard local
implementation of such an object
IPC
(IBinder - class)
● Base interface for a remotable object
● This interface describes abstract protocol for
interacting with a remotable object
IPC
(Binder)
● The data sent through transact() is a Parcel
● Parcel is a generic buffer of data that also
maintains some meta-data about its contents
● The meta data is used to manage IBinder
object references in the buffer, so that those
references can be maintained as the buffer
moves across processes
● “transact()” is internally mapped to
“onTransact()”
IPC
(Binder - Class Hierarchy)
Binder
# onTransact ()
+ transact ()
<<interface>>
IBinder
+ transact ()
Stub
+
<<interface>>
IMyService
+ myMethod ()
● Binder class implements IBinder interface
● Stub extends Binder class
● Your service interface shall extend Stub
● Your Service class shall implement your
service interface
MyService
+ myMethod ()
IPC
(Binder)
Binder Binder
Parcel
onTransact() transact()
Parcel
transact() onTransact()
Process A Process B
Parcel
Parcel
unmarshell() marshell()
marshell() unmarshell()
IPC
(Messenger)
● Messenger - If you want to perform IPC, but do
not need to handle multi-threading,
implement your interface using a Messenger
App Component
App A
App Component
App B
Messenger
IPC
(Architecture)
Service
Stub
App
AIDL Service AIDL Client
Linux KernelBinder
Server process Client process
Dalvik Runtime
Native Runtime
Stub.proxy
Dalvik Runtime
Native Runtime
/dev/binder
Context
IPC
(Architecture)
Proxy
Application System Server
Stub
Manager Service
Service Manager
IBinder
IPC
(Synchronous)
● Synchronous RPC
– The synchronous calls are blocking calls
– Sender waits for the response from remote side
– Synchronous methods may have “out” and “inout”
parameters
– The method must have return type
IPC
(Synchronous)
● Example -
public interface IMathInterface {
int add(int x, int y);
}
IPC
(Asynchronous)
● Asynchronous AIDL interface is defined with
oneway keyword
● Keyword is used either at interface level or on
individual methods
● Asynchronous methods must not have out and
inout arguments
● They must also return void
IPC
(Asynchronous)
● Example -
oneway interface IAsyncInterface {
void methodX(IAsyncCallback callback);
void methodY(IAsyncCallback callback);
}
IPC
(“in”, “out” and “inout”)
● “in” indicates :
– Object is used for input only
– Object is transferred from client to service
– If object is modified in service then change would not be
reflected in client
● “out” indicates :
– The object will be populated and returned by service as
response
● “inout” indicates :
– If any modification is made to the object in service then that
would also be reflected in the client’s object
Adding Custom service
Adding Custom Service
● Step 1 : Writing service
● Step 2 : Writing service manager
● Step 3 : Writing Interface (AIDL, JNI)
● Step 4 : Register Service (context, registry)
● Step 5 : Start Service
● Step 6 : Writing Sepolicy
● Step 7 : Update APIs
Step 1: Writing Service
● Path: /frameworks/base/services/core/java/com/android/server/
● File :MyAwesomeService.java
package com.android.server.myawesome;
...
import android.os.IMyAwesomeService;
import com.android.server.SystemService;
...
public class MyAwesomeService extends SystemService {
private static final String TAG = "MyAwesomeService";
private Context mContext;
…
}
Step 2: Writing Service Manager
● Path : frameworks/base/core/java/android/os
● File : MyAwesomeManager.java
Import android.os.IMyAwesomeService;
Public class MyAwsomeManager {
IMyAwesomeService mService;
private static final String TAG = “MyAwesomeManager”;
….
….
}
Step 3: Write Interface
package android.os;
interface IMyAwesomeService {
...
String read(int maxLength);
...
int write(String mString);
}
● AIDL interface for new service
– Path : frameworks/base/core/java/android/os/
– File : IMyAwesomeService.aidl
Step 3: Write Interface
core/java/android/os/IMyAwesomeService.aidl 
● Add AIDL file in android make file
– Path : /framework/base
– File : Android.mk
Step 3: Write Interface
#include <hardware/myawesome.h>
…
namespace android
{
myawesome_device_t* myawesome_dev;
…
…
};
● JNI interface for new service
– Path : frameworks/base/core/java/android/os/
– File : com_android_server_MyAwesomeService.cpp
Step 3: Write Interface
$(LOCAL_REL_DIR)/com_android_server_MyAwesomeService.cpp 
● Add JNI file in android make file
– Path : /framework/base/services/core/jni
– File : Android.mk
Step 3: Write Interface
int register_android_server_MyAwesomeService(JNIEnv* env);
● Add JNI file in android make file
– Path : /framework/base/services/core/jni
– File : onload.cpp
Step 3: Write Interface
struct myawesome_device_t {
struct hw_device_t common;
int (*read)(char* buffer, int length);
int (*write)(char* buffer, int length);
…
};
struct myawesome_module_t {
struct hw_module_t common;
};
● Add interface file for HAL
– Path : /hardware/libhardware/include/
– File : myawesome.h
Step 4: Register Service
● Update Registry
– Path: /frameworks/base/core/java/android/app
– File : SystemServiceRegistry.java
● Update Context
– Path : /frameworks/base/core/java/android/content
– File : Context.java
Step 5: Start Service
● Path: /frameworks/base/services/java/com/android/server/
● File : SystemServer.java
import com.android.server.myawesome.MyAwesomeService;
…
public class SystemService {
…
private void startOtherServices() {
…
mSystemServiceManager.startService(MyAwesomeService.class);
…
}
…
}
SELinux Policy
● Access control mechanisms
– DAC (Discretionary Access Control)
● Access is provided based on user permission
– MAC (Mandatory Access Control)
● Each program runs within a sandbox that limits its
permissions
SELinux Policy
(MAC vs DAC)
● Generally, MACs are much more effective than
DACs
● MAC are often applied to agents other than
users, such as programs, whereas DACs are
generally applied only to users
● MACs may be applied to objects not protected
by DACs such as network sockets and processes
Step 6: Writing Sepolicy
● Path :
– /device/<vendor>/<product>/sepolicy
– Example : /device/brcm/rpi3/sepolicy
● File(s)
– device.te
– service.te
– service_contexts
– <custom-service>.te (Example : myawesome.te)
*policy configuration files end in .te
Step 6: Writing Sepolicy
● Specify service type (service.te)
type myawesome_service, app_api_service,
system_server_service, service_manager_type;
Step 6: Writing Sepolicy
● Specify service type (device.te)
type myawesome_device, dev_type;
Step 6: Writing Sepolicy
● Writing myawesome.te
type myawesome, domain, domain_deprecated;
app_domain(myawesome)
binder_service(myawesome)
allow myawesome myawesome_device:chr_file
rw_file_perms;
allow myawesome app_api_service:service_manager
find;
allow myawesome system_api_service:service_manager
find;
allow myawesome shell_data_file:file read;
Step 6: Writing Sepolicy
● Writing service_contexts
myawesome u:object_r:myawesome_service:s0
Step 7 : Update APIs
● Android APIs shall be updated for custom service
– make -j4 update-api
● Now, compile AOSP to generate system.img and
ramdisk.img
– make -j4
Custom HAL
struct myawesome_module_t HAL_MODULE_INFO_SYM = {
.common = {
.tag = HARDWARE_MODULE_TAG,
.module_api_version =
MYAWESOME_MODULE_API_VERSION_1_0,
.hal_api_version = HARDWARE_HAL_API_VERSION,
.id = MYAWESOME_HARDWARE_MODULE_ID,
.name = "MyAwesome HAL Module",
.author = "Emertxe",
.methods = &myawesome_module_methods,
.dso = 0,
.reserved = {},
},
};
Compile SDK
● $ source build/envsetup.sh
● $ lunch aosp_x86-eng
● $ make -j4 sdk
● Copy “android.jar” to Android Studio
– Source :
/target/common/obj/PACKAGING/android_jar_intermediates/
– Destination : /android-studio/plugins/android/lib/
Testing custom service
● Write an app in android studio and test
Stay connected
About us: Emertxe is India’s one of the top IT finishing schools & self learning
kits provider. Our primary focus is on Embedded with diversification focus on
Java, Oracle and Android areas
Emertxe Information Technologies Pvt Ltd
No. 83, 1st Floor, Farah Towers,
M.G Road, Bangalore
Karnataka - 560001
T: +91 809 555 7 333
T: +91 80 4128 9576
E: training@emertxe.com
https://www.facebook.com/Emertxe https://twitter.com/EmertxeTweet https://www.slideshare.net/EmertxeSlides
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Opersys inc.
 
Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...
Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...
Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...
Opersys inc.
 

Was ist angesagt? (20)

Embedded Android : System Development - Part IV
Embedded Android : System Development - Part IVEmbedded Android : System Development - Part IV
Embedded Android : System Development - Part IV
 
Q4.11: Porting Android to new Platforms
Q4.11: Porting Android to new PlatformsQ4.11: Porting Android to new Platforms
Q4.11: Porting Android to new Platforms
 
Learning AOSP - Android Linux Device Driver
Learning AOSP - Android Linux Device DriverLearning AOSP - Android Linux Device Driver
Learning AOSP - Android Linux Device Driver
 
Android's HIDL: Treble in the HAL
Android's HIDL: Treble in the HALAndroid's HIDL: Treble in the HAL
Android's HIDL: Treble in the HAL
 
Learning AOSP - Android Booting Process
Learning AOSP - Android Booting ProcessLearning AOSP - Android Booting Process
Learning AOSP - Android Booting Process
 
Low Level View of Android System Architecture
Low Level View of Android System ArchitectureLow Level View of Android System Architecture
Low Level View of Android System Architecture
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
 
Deep Dive into the AOSP
Deep Dive into the AOSPDeep Dive into the AOSP
Deep Dive into the AOSP
 
A deep dive into Android OpenSource Project(AOSP)
A deep dive into Android OpenSource Project(AOSP)A deep dive into Android OpenSource Project(AOSP)
A deep dive into Android OpenSource Project(AOSP)
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Android for Embedded Linux Developers
Android for Embedded Linux DevelopersAndroid for Embedded Linux Developers
Android for Embedded Linux Developers
 
Embedded Android Workshop with Pie
Embedded Android Workshop with PieEmbedded Android Workshop with Pie
Embedded Android Workshop with Pie
 
Android Treble: Blessing or Trouble?
Android Treble: Blessing or Trouble?Android Treble: Blessing or Trouble?
Android Treble: Blessing or Trouble?
 
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
"Learning AOSP" - Android Hardware Abstraction Layer (HAL)
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
Understanding the Android System Server
Understanding the Android System ServerUnderstanding the Android System Server
Understanding the Android System Server
 
Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...
Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...
Native Android Userspace part of the Embedded Android Workshop at Linaro Conn...
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
Android IPC Mechanism
Android IPC MechanismAndroid IPC Mechanism
Android IPC Mechanism
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot images
 

Ähnlich wie Embedded Android : System Development - Part IV (Android System Services)

Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
Muhammad Sajid
 
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
mfrancis
 

Ähnlich wie Embedded Android : System Development - Part IV (Android System Services) (20)

Android101
Android101Android101
Android101
 
GlueCon 2015 - How REST APIs can glue all types of devices together
GlueCon 2015 - How REST APIs can glue all types of devices togetherGlueCon 2015 - How REST APIs can glue all types of devices together
GlueCon 2015 - How REST APIs can glue all types of devices together
 
Displaying google maps in mobileapplication.pptx
Displaying google maps in mobileapplication.pptxDisplaying google maps in mobileapplication.pptx
Displaying google maps in mobileapplication.pptx
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Yotpo microservices
Yotpo microservicesYotpo microservices
Yotpo microservices
 
The Fn Project: A Quick Introduction (December 2017)
The Fn Project: A Quick Introduction (December 2017)The Fn Project: A Quick Introduction (December 2017)
The Fn Project: A Quick Introduction (December 2017)
 
Aidl service
Aidl serviceAidl service
Aidl service
 
Android Development Tutorial
Android Development TutorialAndroid Development Tutorial
Android Development Tutorial
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice Frameworks
 
IPC: AIDL is not a curse
IPC: AIDL is not a curseIPC: AIDL is not a curse
IPC: AIDL is not a curse
 
Integration Microservices
Integration MicroservicesIntegration Microservices
Integration Microservices
 
Faites évoluer votre accès aux données avec MongoDB Stitch
Faites évoluer votre accès aux données avec MongoDB StitchFaites évoluer votre accès aux données avec MongoDB Stitch
Faites évoluer votre accès aux données avec MongoDB Stitch
 
Andriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptxAndriod Lecture 8 A.pptx
Andriod Lecture 8 A.pptx
 
Discover MongoDB Atlas and MongoDB Stitch - DEM02-S - Mexico City AWS Summit
Discover MongoDB Atlas and MongoDB Stitch - DEM02-S - Mexico City AWS SummitDiscover MongoDB Atlas and MongoDB Stitch - DEM02-S - Mexico City AWS Summit
Discover MongoDB Atlas and MongoDB Stitch - DEM02-S - Mexico City AWS Summit
 
Evolving your api architecture with the strangler pattern
Evolving your api architecture with the strangler patternEvolving your api architecture with the strangler pattern
Evolving your api architecture with the strangler pattern
 
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
 
Angular meetup 2 2019-08-29
Angular meetup 2   2019-08-29Angular meetup 2   2019-08-29
Angular meetup 2 2019-08-29
 
Frontend APIs powering fast paced product iterations
Frontend APIs powering fast paced product iterationsFrontend APIs powering fast paced product iterations
Frontend APIs powering fast paced product iterations
 
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
 
MRA AMA: Ingenious: The Journey to Service Mesh using a Microservices Demo App
MRA AMA: Ingenious: The Journey to Service Mesh using a Microservices Demo AppMRA AMA: Ingenious: The Journey to Service Mesh using a Microservices Demo App
MRA AMA: Ingenious: The Journey to Service Mesh using a Microservices Demo App
 

Mehr von Emertxe Information Technologies Pvt Ltd

Mehr von Emertxe Information Technologies Pvt Ltd (20)

premium post (1).pdf
premium post (1).pdfpremium post (1).pdf
premium post (1).pdf
 
Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Embedded Android : System Development - Part IV (Android System Services)

  • 1. Team Emertxe Android System Development Day-4
  • 3. ● Introduction to service ● Inter Process Communication (IPC) ● Adding Custom Service ● Writing Custom HAL ● Compiling SDK ● Testing Custom Service Table of Content
  • 5. “A Service is an application component that can perform long-running operations in the background and does not provide a user interface” “A Service is an application component that can perform long-running operations in the background and does not provide a user interface” ● Another app 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) ● Example - play music, download a file, tracking distance traveled through sensor, all from the background Introduction to Service (what?)
  • 6. Introduction to Service (what?) ● Service is not process ● Faceless task that runs in the background ● No visual user interface ● Can run indefinitely unless stopped ● Each service extends the Service base class
  • 7. Introduction to Service (Types) ● Scheduled ● Started ● Bound
  • 8. Introduction to Service (Types - Scheduled) ● A service is scheduled through JobScheduler ● JobScheduler API was introduced in Android 5.0 (API level 21) ● API is used for scheduling various types of jobs against the framework that will be executed in app’s own process ● Example : – Cricket score update
  • 9. Introduction to Service (Types - Started) ● A service is started when an application component (such as an activity) calls startService() ● After it's started, a service can run in background indefinitely, even if the component that started it is destroyed ● Usually, a started service performs a single operation and does not return a result to the caller ● Example : download or upload a file over the network ● When operation is complete, service should stop itself
  • 10. Introduction to Service (Types - Bound) “A bound service is the server in a client-server interface. It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC)” “A bound service is the server in a client-server interface. It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC)” ● A bound service typically lives only while it serves another app component and does not run in the background indefinitely ● Example : GPS service
  • 11. Introduction to Service (Types - Bound) ● A service is bound when an app component binds to it by calling bindService() ● A bound service runs only as long as another app component is bound to it ● Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed
  • 12. Introduction to Service (Basics) ● A service can be started (to run indefinitely), bound or both ● Any app component can use the service (even from a separate application) in the same way that any component can use an activity—by starting it with an Intent ● If required, declare the service as private in manifest file and block access from other app
  • 13. Introduction to Service (Basics) ● A service runs in the main thread of its hosting process ● The service does not create its own thread and does not run in a separate process unless specified Services expected to do CPU-intensive work or blocking operations, such as MP3 playback or networking, shall create a new thread within the service to complete that work Separate thread reduces the risk of “Application Not Responding” (ANR) errors, and apps main thread can remain dedicated to user interaction with activities
  • 16. IPC (Different ways) ● AIDL ● Binder ● Message
  • 17. IPC (AIDL) “Android Interface Definition Language (AIDL) enables to define programming interface that both client and service agree upon in order to communicate with each other using inter-process communication (IPC)” “Android Interface Definition Language (AIDL) enables to define programming interface that both client and service agree upon in order to communicate with each other using inter-process communication (IPC)”
  • 18. IPC (AIDL) AIDL usage is necessary only if you allow clients from different applications to access your service for IPC and want to handle multi- threading in your service AIDL usage is necessary only if you allow clients from different applications to access your service for IPC and want to handle multi- threading in your service Example : A sensor hub service catering to different requests from multiple apps
  • 19. IPC (AIDL - why?) ● In Android, one process cannot normally access the memory of another process ● So processes need to decompose their objects into primitives that operating system can understand ● These primitives are marshalled by OS across process boundary ● The marshalling code is tedious to write, so Android handles it with AIDL
  • 20. AIDL (usage) App1 App2 App3 . . . Service AIDL
  • 21. IPC (Binder) ● Create your interface by extending Binder if - – There is no need to perform concurrent IPC across different apps – Your service is private to your own application and runs in the same process as the client (your service is merely a background worker for your own app)
  • 22. IPC (Binder - usage) App Component A Service App Component B App
  • 23. IPC (Binder - class) ● Binder is base class for a remotable object ● Binder class implements IBinder interface ● IBinder provides standard local implementation of such an object
  • 24. IPC (IBinder - class) ● Base interface for a remotable object ● This interface describes abstract protocol for interacting with a remotable object
  • 25. IPC (Binder) ● The data sent through transact() is a Parcel ● Parcel is a generic buffer of data that also maintains some meta-data about its contents ● The meta data is used to manage IBinder object references in the buffer, so that those references can be maintained as the buffer moves across processes ● “transact()” is internally mapped to “onTransact()”
  • 26. IPC (Binder - Class Hierarchy) Binder # onTransact () + transact () <<interface>> IBinder + transact () Stub + <<interface>> IMyService + myMethod () ● Binder class implements IBinder interface ● Stub extends Binder class ● Your service interface shall extend Stub ● Your Service class shall implement your service interface MyService + myMethod ()
  • 27. IPC (Binder) Binder Binder Parcel onTransact() transact() Parcel transact() onTransact() Process A Process B Parcel Parcel unmarshell() marshell() marshell() unmarshell()
  • 28. IPC (Messenger) ● Messenger - If you want to perform IPC, but do not need to handle multi-threading, implement your interface using a Messenger App Component App A App Component App B Messenger
  • 29. IPC (Architecture) Service Stub App AIDL Service AIDL Client Linux KernelBinder Server process Client process Dalvik Runtime Native Runtime Stub.proxy Dalvik Runtime Native Runtime /dev/binder
  • 31. IPC (Synchronous) ● Synchronous RPC – The synchronous calls are blocking calls – Sender waits for the response from remote side – Synchronous methods may have “out” and “inout” parameters – The method must have return type
  • 32. IPC (Synchronous) ● Example - public interface IMathInterface { int add(int x, int y); }
  • 33. IPC (Asynchronous) ● Asynchronous AIDL interface is defined with oneway keyword ● Keyword is used either at interface level or on individual methods ● Asynchronous methods must not have out and inout arguments ● They must also return void
  • 34. IPC (Asynchronous) ● Example - oneway interface IAsyncInterface { void methodX(IAsyncCallback callback); void methodY(IAsyncCallback callback); }
  • 35. IPC (“in”, “out” and “inout”) ● “in” indicates : – Object is used for input only – Object is transferred from client to service – If object is modified in service then change would not be reflected in client ● “out” indicates : – The object will be populated and returned by service as response ● “inout” indicates : – If any modification is made to the object in service then that would also be reflected in the client’s object
  • 37. Adding Custom Service ● Step 1 : Writing service ● Step 2 : Writing service manager ● Step 3 : Writing Interface (AIDL, JNI) ● Step 4 : Register Service (context, registry) ● Step 5 : Start Service ● Step 6 : Writing Sepolicy ● Step 7 : Update APIs
  • 38. Step 1: Writing Service ● Path: /frameworks/base/services/core/java/com/android/server/ ● File :MyAwesomeService.java package com.android.server.myawesome; ... import android.os.IMyAwesomeService; import com.android.server.SystemService; ... public class MyAwesomeService extends SystemService { private static final String TAG = "MyAwesomeService"; private Context mContext; … }
  • 39. Step 2: Writing Service Manager ● Path : frameworks/base/core/java/android/os ● File : MyAwesomeManager.java Import android.os.IMyAwesomeService; Public class MyAwsomeManager { IMyAwesomeService mService; private static final String TAG = “MyAwesomeManager”; …. …. }
  • 40. Step 3: Write Interface package android.os; interface IMyAwesomeService { ... String read(int maxLength); ... int write(String mString); } ● AIDL interface for new service – Path : frameworks/base/core/java/android/os/ – File : IMyAwesomeService.aidl
  • 41. Step 3: Write Interface core/java/android/os/IMyAwesomeService.aidl ● Add AIDL file in android make file – Path : /framework/base – File : Android.mk
  • 42. Step 3: Write Interface #include <hardware/myawesome.h> … namespace android { myawesome_device_t* myawesome_dev; … … }; ● JNI interface for new service – Path : frameworks/base/core/java/android/os/ – File : com_android_server_MyAwesomeService.cpp
  • 43. Step 3: Write Interface $(LOCAL_REL_DIR)/com_android_server_MyAwesomeService.cpp ● Add JNI file in android make file – Path : /framework/base/services/core/jni – File : Android.mk
  • 44. Step 3: Write Interface int register_android_server_MyAwesomeService(JNIEnv* env); ● Add JNI file in android make file – Path : /framework/base/services/core/jni – File : onload.cpp
  • 45. Step 3: Write Interface struct myawesome_device_t { struct hw_device_t common; int (*read)(char* buffer, int length); int (*write)(char* buffer, int length); … }; struct myawesome_module_t { struct hw_module_t common; }; ● Add interface file for HAL – Path : /hardware/libhardware/include/ – File : myawesome.h
  • 46. Step 4: Register Service ● Update Registry – Path: /frameworks/base/core/java/android/app – File : SystemServiceRegistry.java ● Update Context – Path : /frameworks/base/core/java/android/content – File : Context.java
  • 47. Step 5: Start Service ● Path: /frameworks/base/services/java/com/android/server/ ● File : SystemServer.java import com.android.server.myawesome.MyAwesomeService; … public class SystemService { … private void startOtherServices() { … mSystemServiceManager.startService(MyAwesomeService.class); … } … }
  • 48. SELinux Policy ● Access control mechanisms – DAC (Discretionary Access Control) ● Access is provided based on user permission – MAC (Mandatory Access Control) ● Each program runs within a sandbox that limits its permissions
  • 49. SELinux Policy (MAC vs DAC) ● Generally, MACs are much more effective than DACs ● MAC are often applied to agents other than users, such as programs, whereas DACs are generally applied only to users ● MACs may be applied to objects not protected by DACs such as network sockets and processes
  • 50. Step 6: Writing Sepolicy ● Path : – /device/<vendor>/<product>/sepolicy – Example : /device/brcm/rpi3/sepolicy ● File(s) – device.te – service.te – service_contexts – <custom-service>.te (Example : myawesome.te) *policy configuration files end in .te
  • 51. Step 6: Writing Sepolicy ● Specify service type (service.te) type myawesome_service, app_api_service, system_server_service, service_manager_type;
  • 52. Step 6: Writing Sepolicy ● Specify service type (device.te) type myawesome_device, dev_type;
  • 53. Step 6: Writing Sepolicy ● Writing myawesome.te type myawesome, domain, domain_deprecated; app_domain(myawesome) binder_service(myawesome) allow myawesome myawesome_device:chr_file rw_file_perms; allow myawesome app_api_service:service_manager find; allow myawesome system_api_service:service_manager find; allow myawesome shell_data_file:file read;
  • 54. Step 6: Writing Sepolicy ● Writing service_contexts myawesome u:object_r:myawesome_service:s0
  • 55. Step 7 : Update APIs ● Android APIs shall be updated for custom service – make -j4 update-api ● Now, compile AOSP to generate system.img and ramdisk.img – make -j4
  • 56. Custom HAL struct myawesome_module_t HAL_MODULE_INFO_SYM = { .common = { .tag = HARDWARE_MODULE_TAG, .module_api_version = MYAWESOME_MODULE_API_VERSION_1_0, .hal_api_version = HARDWARE_HAL_API_VERSION, .id = MYAWESOME_HARDWARE_MODULE_ID, .name = "MyAwesome HAL Module", .author = "Emertxe", .methods = &myawesome_module_methods, .dso = 0, .reserved = {}, }, };
  • 57. Compile SDK ● $ source build/envsetup.sh ● $ lunch aosp_x86-eng ● $ make -j4 sdk ● Copy “android.jar” to Android Studio – Source : /target/common/obj/PACKAGING/android_jar_intermediates/ – Destination : /android-studio/plugins/android/lib/
  • 58. Testing custom service ● Write an app in android studio and test
  • 59. Stay connected About us: Emertxe is India’s one of the top IT finishing schools & self learning kits provider. Our primary focus is on Embedded with diversification focus on Java, Oracle and Android areas Emertxe Information Technologies Pvt Ltd No. 83, 1st Floor, Farah Towers, M.G Road, Bangalore Karnataka - 560001 T: +91 809 555 7 333 T: +91 80 4128 9576 E: training@emertxe.com https://www.facebook.com/Emertxe https://twitter.com/EmertxeTweet https://www.slideshare.net/EmertxeSlides