Services Broadcast Receivers Permissions
Runs in the background Extends Service Java class Not necessarily connected to the user s visual interface
Music player working in foreground User wants read email Music player should continue playing in background
1. Implement onserviceconnected, onservicedisconnected 2. bind to the service 3. Hope bind returns with permission granted so you can start using the service
Your application needs to implement onserviceconnected and onservicedisconnected because you need to know what to do as soon as a connection has been established and disconnected You also need to bind to the service
call Context.bindService(Intent, ServiceConnection, flags) If the Service is not running, bindservice() can start it
Just because you request a service doesn t mean you ll get it. onbind can DENY you permission Or onbind can GRANT permission. In which case you have gained access to the service and created a communication channel More on Android s permission architecture later
Write your own Service
Extend from Service class. You need to implement the onstart method which gets called when the service is started If you want others to connect to your service, you ll need to implement onbind
You can register it within AndroidManifest.XML Let Android know your application has a Service component <service android:enabled=["true" "false"] android:exported[="true" "false"] android:icon="drawable resource" android:label="string resource" android:name="com.example.project.roomservice" android:permission="string" android:process="string" >... </service>
Clients of the service would implement onserviceconnected() and onservicedisconnected() methods so they can be notified when a successful connection to the remote service is established, and when it goes away. They would then call bindservice() to set up the connection. The service's onbind() method would be implemented to either accept or reject the connection, depending on the intent it receives (the intent passed to bindservice()). If the service accepts the connection, Android calls the client's onserviceconnected() method and passes it a proxy. Through the proxy, the client can make calls on the remote service.
Java object called IBinder Base interface for a remotable object, the core part of a lightweight remote procedure call mechanism designed for high performance when performing in- process and cross- process calls. This interface describes the abstract protocol for interacting with a remotable object.
Component that receives and reacts to broadcast announcements Announcements are Intents No user interface Extends BroadcastReceiver Java class
Broadcast receiver registers for announcements Announcement broadcast System identifies recipient and calls onreceive(context,intent) onreceive() implements response
You can register it within AndroidManifest.XML Let Android know your application has a Broadcast Receiver component <receiver android:enabled=["true" "false"] android:exported=["true" "false"] android:icon="drawable resource" android:label="string resource" android:name="string" android:permission="string" android:process="string" >... </receiver>
Context.registerReceiver(receiver,intentfilter) This registers receiver to watch for intents that match intentfilter
SYSTEM announcements Time zone change Battery is low User changed language preferences Picture has been taken
* Use the Activity application component Specifically, Context.sendBroadcast(Intent) Sending the broadcast from an Activity would eventually get to the onreceive(intent) function of a particular BroadcastReceiver Java class All receivers matching this Intent will receive the broadcast.
Example of on onreceive()
Because a process running a service is ranked higher than one with background activities, an activity that initiates a long- running operation might do well to start a service for that operation, rather than simply spawn a thread particularly if the operation will likely outlast the activity. Priority(Service) > Priority(Background)
You have a client and server. The client wants to execute a service which only the server can do The client is running in an Android OS process The server is also running in an Android OS process (may or may not be the same as the client s) The client has it s own address space The server has it s own address space The only way these two seemingly independent entities can communicate is with something they share: Android OS
Android has a lightweight mechanism for remote procedure calls (RPCs) where a method is called locally, but executed remotely (in another process), with any result returned back to the caller. This entails decomposing the method call and all its attendant data to a level the operating system can understand, transmitting it from the local process and address space to the remote process and address space, and reassembling and reenacting the call there. Return values have to be transmitted in the opposite direction. Android provides all the code to do that work, so that you can concentrate on defining and implementing the RPC interface itself
AIDL (Android Interface Definition Language) is an IDL language used to generate code that enables two processes on an Android- powered device to talk using interprocess communication (IPC). If you have code in one process (for example, in an Activity) that needs to call methods on an object in another process (for example, a Service), you would use AIDL to generate code to marshall the parameters.
package com.example.android.apis.app; /** * Example of a secondary interface associated with a service. (Note that * the interface itself doesn't impact, it is just a matter of how you * retrieve it from the service.) */ interface ISecondary { /** * Request the PID of this service, to do evil things with it. */ int getpid(); /** * This demonstrates the basic types that you can use as parameters * and return values in AIDL. */ void basictypes(int anint, long along, boolean aboolean, float afloat, double adouble, String astring); }
161 lines of Java code Thanks to AIDL Tool (which Eclipse ADT Plugin automatically configured to use) You can also create this Java file by going to $ANDROID_SDK/tools/aidl <input=isecondary.aidl>
Includes an abstract inner class named Stub that declares all the methods that you declared in your.aidl file Stub also defines a few helper methods: asinterface() - takes an IBinder (passed to a client's onserviceconnected() implementation when applicationcontext.bindservice() succeeds), and returns an instance of the interface used to call the IPC methods
To implement your interface, extend YourInterface.Stub, and implement the methods. Where YourInterface = ISecondary.Stub for our example
No exceptions that you throw will be sent back to the caller. By default, IPC calls are synchronous. If you know that an IPC service takes more than a few milliseconds to complete, you should not call it in the Activity/View thread, because it might hang the application (Android might display an "Application is Not Responding" dialog). Try to call them in a separate thread. Only methods are supported; you cannot declare static fields in an AIDL interface.
Publish it Inherit Service and implement Service.onBind(Intent) to return an instance of the class that implements your interface.
STEP #1: Declare a variable of the interface type that your.aidl file defined. msecondaryservice = ISecondary.Stub.asInterface(service);
STEP #2: Implement ServiceConnection. Interface for monitoring the state of an application service. Basically implement onserviceconnected() and onservicedisconnected()
STEP #3: Call Context.bindService(), passing in your ServiceConnection implementation in step #2
STEP #4: In your implementation of ServiceConnection.onServiceConnected(), you will receive an IBinder instance (called service). Call YourInterfaceName.Stub.asInterface((IBinder) service) to cast the returned parameter to YourInterface type.
Step #5: Call the methods that you defined on your interface. You should always trap DeadObjectException exceptions, which are thrown when the connection has broken; this will be the only exception thrown by remote methods.
Step #6: To disconnect, call Context.unbindService() with the instance of your interface.
None of the previous slides would matter if you do not have permission to bind to a service
mechanism that enforces restrictions on the specific operations that a particular process can perform
An application's process runs in a security sandbox. The sandbox is designed to prevent applications from disrupting each other, except by explicitly declaring the permissions they need for additional capabilities not provided by the basic sandbox.
If you want others to access your application s DeadlyActivity it needs to defined in AndroidManifest.xml Example:
Client wants to add two numbers Client wants to connect to the service that does that. Write a service that will accept two integers, add them, and return the sum to the client. Additionally, the server app will be listening for clients connecting and requesting its service. When a client connects to it, the server app will send out a broadcast announcement saying a client has connected. Your client app should receive this announcement and print an alert message on its screen