Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信
Android Interface Definition Language (AIDL)
AIDL (Android Interface Definition Language) is similar to other IDLs you might have worked with. It allows you to define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC). On Android, one process cannot normally access the memory of another process. So to talk, they need to decompose their objects into primitives that the operating system can understand, and marshall the objects across that boundary for you. The code to do that marshalling is tedious to write, so Android handles it for you with AIDL.
Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Regardless, be sure that you understand Bound Services before implementing an AIDL.
注意:只在你的服务需要跨进程通信并且处理多线程时,才用的到AIDL,跨进程单线程时Messenger就可以搞定。
Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are direct function calls. You should not make assumptions about the thread in which the call occurs. What happens is different depending on whether the call is from a thread in the local process or a remote process. Specifically:
- Calls made from the local process are executed in the same thread that is making the call. If this is your main UI thread, that thread continues to execute in the AIDL interface. If it is another thread, that is the one that executes your code in the service. Thus, if only local threads are accessing the service, you can completely control which threads are executing in it (but if that is the case, then you shouldn't be using AIDL at all, but should instead create the interface by implementing a Binder).
- Calls from a remote process are dispatched from a thread pool the platform maintains inside of your own process. You must be prepared for incoming calls from unknown threads, with multiple calls happening at the same time. In other words, an implementation of an AIDL interface must be completely thread-safe.
- The
oneway
keyword modifies the behavior of remote calls. When used, a remote call does not block; it simply sends the transaction data and immediately returns. The implementation of the interface eventually receives this as a regular call from theBinder
thread pool as a normal remote call. Ifoneway
is used with a local call, there is no impact and the call is still synchronous.
2.Defining an AIDL Interface
2.1 简介
You must define your AIDL interface in an .aidl
file using the Java programming language syntax, then save it in the source code (in the src/
directory) of both the application hosting the service and any other application that binds to the service.
.aidl 文件内定义在服务端、客户端使用的接口,这个文件在两边都要存在。
When you build each application that contains the .aidl
file, the Android SDK tools generate an IBinder
interface based on the .aidl
file and save it in the project's gen/
directory. The service must implement the IBinder
interface as appropriate. The client applications can then bind to the service and call methods from the IBinder
to perform IPC.
Android SDK 工具会根据.aidl文件生成相应接口,在 gen/目录下。
To create a bounded service using AIDL, follow these steps: AIDL步骤
- Create the .aidl file
This file defines the programming interface with method signatures.
- Implement the interface
The Android SDK tools generate an interface in the Java programming language, based on your
.aidl
file. This interface has an inner abstract class namedStub
that extendsBinder
and implements methods from your AIDL interface. You must extend theStub
class and implement the methods. - Expose the interface to clients
Implement a
Service
and overrideonBind()
to return your implementation of theStub
class.
Caution: Any changes that you make to your AIDL interface after your first release must remain backward compatible in order to avoid breaking other applications that use your service. That is, because your .aidl
file must be copied to other applications in order for them to access your service's interface, you must maintain support for the original interface.
在.aidl文件中定义接口时要注意兼容问题,因为它可能被拷贝到多个其它应用的代码中。
2.2 Create the .aidl file
AIDL uses a simple syntax that lets you declare an interface with one or more methods that can take parameters and return values. The parameters and return values can be of any type, even other AIDL-generated interfaces.
注意使用as时,要在使用.aidl接口的包下点生成aidl文件。不然生成到根包下,容易找不到定义。
.aidl中声明的参数和返回值可以是任意类型,甚至可以是在其它.aidl的定义的类型。
You must construct the .aidl
file using the Java programming language. Each .aidl
file must define a single interface and requires only the interface declaration and method signatures.
By default, AIDL supports the following data types:
AIDL支持的数据类型如下:
- All primitive types in the Java programming language (such as
int
,long
,char
,boolean
, and so on) String
CharSequence
List
All elements in the
List
must be one of the supported data types in this list or one of the other AIDL-generated interfaces or parcelables you've declared. AList
may optionally be used as a "generic" class (for example,List<String>
). The actual concrete class that the other side receives is always anArrayList
, although the method is generated to use theList
interface.注意,这里是List接口,其中的元素要实现parcelable,通常使用的是ArrayList。
Map
All elements in the
Map
must be one of the supported data types in this list or one of the other AIDL-generated interfaces or parcelables you've declared. Generic maps, (such as those of the formMap<String,Integer>
are not supported. The actual concrete class that the other side receives is always aHashMap
, although the method is generated to use theMap
interface.Map内的元素也要实现Parcelable,但是
Map<String,Integer>
不支持。
You must include an import
statement for each additional type not listed above, even if they are defined in the same package as your interface.
When defining your service interface, be aware that:
以下几点也要注意:
- Methods can take zero or more parameters, and return a value or void.
- All non-primitive parameters require a directional tag indicating which way the data goes. Either
in
,out
, orinout
(see the example below).Primitives are
in
by default, and cannot be otherwise.非基本数据类型要用,in,out,inout标示出数据的流动方向。基本类型默认用in标示。
Caution: You should limit the direction to what is truly needed, because marshalling parameters is expensive.
- All code comments included in the
.aidl
file are included in the generatedIBinder
interface (except for comments before the import and package statements).在package com.xxxx.xx和import以后的注释都被原样拷贝到生成的IBinder接口中。
- Only methods are supported; you cannot expose static fields in AIDL.
Here is an example .aidl
file:
1 // IRemoteService.aidl 2 // package前的注释不拷贝。 3 package com.example.android; 4 5 // Declare any non-default types here with import statements 6 7 /** Example service interface */ 8 interface IRemoteService { 9 /** Request the process ID of this service, to do evil things with it. */ 10 int getPid(); 11 12 /** Demonstrates some basic types that you can use as parameters 13 * and return values in AIDL. 14 */ 15 void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, 16 double aDouble, String aString); 17 }
Simply save your .aidl
file in your project's src/
directory and when you build your application, the SDK tools generate the IBinder
interface file in your project's gen/
directory. The generated file name matches the .aidl
file name, but with a .java
extension (for example, IRemoteService.aidl
results in IRemoteService.java
).
IRemoteService.aidl最终在gen/下生成IRemoteService.java
If you use Android Studio, the incremental build generates the binder class almost immediately. If you do not use Android Studio, then the Gradle tool generates the binder class next time you build your application—you should build your project with gradle assembleDebug
(or gradle assembleRelease
) as soon as you're finished writing the .aidl
file, so that your code can link against the generated class.
2.3 Implement the interface
When you build your application, the Android SDK tools generate a .java
interface file named after your .aidl
file. The generated interface includes a subclass named Stub
that is an abstract implementation of its parent interface (for example, YourInterface.Stub
) and declares all the methods from the .aidl
file.
Note: Stub
also defines a few helper methods, most notably asInterface()
, which takes an IBinder
(usually the one passed to a client's onServiceConnected()
callback method) and returns an instance of the stub interface. See the section Calling an IPC Method for more details on how to make this cast.
To implement the interface generated from the .aidl
, extend the generated Binder
interface (for example, YourInterface.Stub
) and implement the methods inherited from the .aidl
file.
Here is an example implementation of an interface called IRemoteService
(defined by the IRemoteService.aidl
example, above) using an anonymous instance:
1 private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { 2 public int getPid(){ 3 return Process.myPid(); 4 } 5 public void basicTypes(int anInt, long aLong, boolean aBoolean, 6 float aFloat, double aDouble, String aString) { 7 // Does nothing 8 } 9 };
Now the mBinder
is an instance of the Stub
class (a Binder
), which defines the RPC interface for the service. In the next step, this instance is exposed to clients so they can interact with the service.
There are a few rules you should be aware of when implementing your AIDL interface:
实现AIDL接口的注意事项:
- Incoming calls are not guaranteed to be executed on the main thread, so you need to think about multithreading from the start and properly build your service to be thread-safe.
- By default, RPC calls are synchronous. If you know that the service takes more than a few milliseconds to complete a request, you should not call it from the activity's main thread, because it might hang the application (Android might display an "Application is Not Responding" dialog)—you should usually call them from a separate thread in the client.
远程调用通常是同步的,不要在main线程进行远程调用。要启新线程。
- No exceptions that you throw are sent back to the caller.
2.4 Expose the interface to clients
Once you've implemented the interface for your service, you need to expose it to clients so they can bind to it. To expose the interface for your service, extend Service
and implement onBind()
to return an instance of your class that implements the generated Stub
(as discussed in the previous section). Here's an example service that exposes the IRemoteService
example interface to clients.
1 public class RemoteService extends Service { 2 @Override 3 public void onCreate() { 4 super.onCreate(); 5 } 6 7 @Override 8 public IBinder onBind(Intent intent) { 9 // Return the interface 10 return mBinder; 11 } 12 13 private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { 14 public int getPid(){ 15 return Process.myPid(); 16 } 17 public void basicTypes(int anInt, long aLong, boolean aBoolean, 18 float aFloat, double aDouble, String aString) { 19 // Does nothing 20 } 21 }; 22 }
Now, when a client (such as an activity) calls bindService()
to connect to this service, the client's onServiceConnected()
callback receives the mBinder
instance returned by the service's onBind()
method.
The client must also have access to the interface class, so if the client and service are in separate applications, then the client's application must have a copy of the .aidl
file in its src/
directory (which generates the android.os.Binder
interface—providing the client access to the AIDL methods).
如果客户端和服务器不在同一个应用内,那么要把.aidl文件拷贝到客户端代码中。
When the client receives the IBinder
in the onServiceConnected()
callback, it must call YourServiceInterface.Stub.asInterface(service)
to cast the returned parameter to YourServiceInterface
type. For example:
1 IRemoteService mIRemoteService; 2 private ServiceConnection mConnection = new ServiceConnection() { 3 // Called when the connection with the service is established 4 public void onServiceConnected(ComponentName className, IBinder service) { 5 // Following the example above for an AIDL interface, 6 // this gets an instance of the IRemoteInterface, which we can use to call on the service 7 mIRemoteService = IRemoteService.Stub.asInterface(service); 8 } 9 10 // Called when the connection with the service disconnects unexpectedly 11 public void onServiceDisconnected(ComponentName className) { 12 Log.e(TAG, "Service has unexpectedly disconnected"); 13 mIRemoteService = null; 14 } 15 };
For more sample code, see the RemoteService.java
class in ApiDemos.
3.Passing Objects over IPC 远程通信传递对象
If you have a class that you would like to send from one process to another through an IPC interface, you can do that. However, you must ensure that the code for your class is available to the other side of the IPC channel and your class must support the Parcelable
interface. Supporting the Parcelable
interface is important because it allows the Android system to decompose objects into primitives that can be marshalled across processes.
To create a class that supports the Parcelable
protocol, you must do the following:
想要通过IPC在不同进程间传递的对象必需是Parcelable,实现它的步骤如下:
- Make your class implement the
Parcelable
interface. - Implement
writeToParcel
, which takes the current state of the object and writes it to aParcel
. - Add a static field called
CREATOR
to your class which is an object implementing theParcelable.Creator
interface. - Finally, create an
.aidl
file that declares your parcelable class (as shown for theRect.aidl
file, below).If you are using a custom build process, do not add the
.aidl
file to your build. Similar to a header file in the C language, this.aidl
file isn't compiled..aidl文件在客户端就像c的头文件一样。
AIDL uses these methods and fields in the code it generates to marshall and unmarshall your objects.
For example, here is a Rect.aidl
file to create a Rect
class that's parcelable:
1 package android.graphics; 2 3 // Declare Rect so AIDL can find it and knows that it implements 4 // the parcelable protocol. 5 parcelable Rect;
And here is an example of how the Rect
class implements the Parcelable
protocol.
1 import android.os.Parcel; 2 import android.os.Parcelable; 3 4 public final class Rect implements Parcelable { 5 public int left; 6 public int top; 7 public int right; 8 public int bottom; 9 10 public static final Parcelable.Creator<Rect> CREATOR = new 11 Parcelable.Creator<Rect>() { 12 public Rect createFromParcel(Parcel in) { 13 return new Rect(in); 14 } 15 16 public Rect[] newArray(int size) { 17 return new Rect[size]; 18 } 19 }; 20 21 public Rect() { 22 } 23 24 private Rect(Parcel in) { 25 readFromParcel(in); 26 } 27 28 public void writeToParcel(Parcel out) { 29 out.writeInt(left); 30 out.writeInt(top); 31 out.writeInt(right); 32 out.writeInt(bottom); 33 } 34 35 public void readFromParcel(Parcel in) { 36 left = in.readInt(); 37 top = in.readInt(); 38 right = in.readInt(); 39 bottom = in.readInt(); 40 } 41 }
The marshalling in the Rect
class is pretty simple. Take a look at the other methods on Parcel
to see the other kinds of values you can write to a Parcel.
Warning: Don't forget the security implications of receiving data from other processes. In this case, the Rect
reads four numbers from the Parcel
, but it is up to you to ensure that these are within the acceptable range of values for whatever the caller is trying to do. See Security and Permissions for more information about how to keep your application secure from malware.
4.Calling an IPC Method 调用远程方法
Here are the steps a calling class must take to call a remote interface defined with AIDL:
- Include the
.aidl
file in the projectsrc/
directory. - Declare an instance of the
IBinder
interface (generated based on the AIDL). - Implement
ServiceConnection
. - Call
Context.bindService()
, passing in yourServiceConnection
implementation. - In your implementation of
onServiceConnected()
, you will receive anIBinder
instance (calledservice
). CallYourInterfaceName.Stub.asInterface((IBinder)service)
to cast the returned parameter to YourInterface type. - 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. - To disconnect, call
Context.unbindService()
with the instance of your interface.
A few comments on calling an IPC service:
- Objects are reference counted across processes.
进程间通过引用计数持有对象?
- You can send anonymous objects as method arguments.
可以传递匿名对象当方法参数。
For more information about binding to a service, read the Bound Services document.
Here is some sample code demonstrating calling an AIDL-created service, taken from the Remote Service sample in the ApiDemos project.
1 public static class Binding extends Activity { 2 /** The primary interface we will be calling on the service. */ 3 IRemoteService mService = null; 4 /** Another interface we use on the service. */ 5 ISecondary mSecondaryService = null; 6 7 Button mKillButton; 8 TextView mCallbackText; 9 10 private boolean mIsBound; 11 12 /** 13 * Standard initialization of this activity. Set up the UI, then wait 14 * for the user to poke it before doing anything. 15 */ 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 20 setContentView(R.layout.remote_service_binding); 21 22 // Watch for button clicks. 23 Button button = (Button)findViewById(R.id.bind); 24 button.setOnClickListener(mBindListener); 25 button = (Button)findViewById(R.id.unbind); 26 button.setOnClickListener(mUnbindListener); 27 mKillButton = (Button)findViewById(R.id.kill); 28 mKillButton.setOnClickListener(mKillListener); 29 mKillButton.setEnabled(false); 30 31 mCallbackText = (TextView)findViewById(R.id.callback); 32 mCallbackText.setText("Not attached."); 33 } 34 35 /** 36 * Class for interacting with the main interface of the service. 37 */ 38 private ServiceConnection mConnection = new ServiceConnection() { 39 public void onServiceConnected(ComponentName className, 40 IBinder service) { 41 // This is called when the connection with the service has been 42 // established, giving us the service object we can use to 43 // interact with the service. We are communicating with our 44 // service through an IDL interface, so get a client-side 45 // representation of that from the raw service object. 46 mService = IRemoteService.Stub.asInterface(service); 47 mKillButton.setEnabled(true); 48 mCallbackText.setText("Attached."); 49 50 // We want to monitor the service for as long as we are 51 // connected to it. 52 try { 53 mService.registerCallback(mCallback); 54 } catch (RemoteException e) { 55 // In this case the service has crashed before we could even 56 // do anything with it; we can count on soon being 57 // disconnected (and then reconnected if it can be restarted) 58 // so there is no need to do anything here. 59 } 60 61 // As part of the sample, tell the user what happened. 62 Toast.makeText(Binding.this, R.string.remote_service_connected, 63 Toast.LENGTH_SHORT).show(); 64 } 65 66 public void onServiceDisconnected(ComponentName className) { 67 // This is called when the connection with the service has been 68 // unexpectedly disconnected -- that is, its process crashed. 69 mService = null; 70 mKillButton.setEnabled(false); 71 mCallbackText.setText("Disconnected."); 72 73 // As part of the sample, tell the user what happened. 74 Toast.makeText(Binding.this, R.string.remote_service_disconnected, 75 Toast.LENGTH_SHORT).show(); 76 } 77 }; 78 79 /** 80 * Class for interacting with the secondary interface of the service. 81 */ 82 private ServiceConnection mSecondaryConnection = new ServiceConnection() { 83 public void onServiceConnected(ComponentName className, 84 IBinder service) { 85 // Connecting to a secondary interface is the same as any 86 // other interface. 87 mSecondaryService = ISecondary.Stub.asInterface(service); 88 mKillButton.setEnabled(true); 89 } 90 91 public void onServiceDisconnected(ComponentName className) { 92 mSecondaryService = null; 93 mKillButton.setEnabled(false); 94 } 95 }; 96 97 private OnClickListener mBindListener = new OnClickListener() { 98 public void onClick(View v) { 99 // Establish a couple connections with the service, binding 100 // by interface names. This allows other applications to be 101 // installed that replace the remote service by implementing 102 // the same interface. 103 Intent intent = new Intent(Binding.this, RemoteService.class); 104 intent.setAction(IRemoteService.class.getName()); 105 bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 106 intent.setAction(ISecondary.class.getName()); 107 bindService(intent, mSecondaryConnection, Context.BIND_AUTO_CREATE); 108 mIsBound = true; 109 mCallbackText.setText("Binding."); 110 } 111 }; 112 113 private OnClickListener mUnbindListener = new OnClickListener() { 114 public void onClick(View v) { 115 if (mIsBound) { 116 // If we have received the service, and hence registered with 117 // it, then now is the time to unregister. 118 if (mService != null) { 119 try { 120 mService.unregisterCallback(mCallback); 121 } catch (RemoteException e) { 122 // There is nothing special we need to do if the service 123 // has crashed. 124 } 125 } 126 127 // Detach our existing connection. 128 unbindService(mConnection); 129 unbindService(mSecondaryConnection); 130 mKillButton.setEnabled(false); 131 mIsBound = false; 132 mCallbackText.setText("Unbinding."); 133 } 134 } 135 }; 136 137 private OnClickListener mKillListener = new OnClickListener() { 138 public void onClick(View v) { 139 // To kill the process hosting our service, we need to know its 140 // PID. Conveniently our service has a call that will return 141 // to us that information. 142 if (mSecondaryService != null) { 143 try { 144 int pid = mSecondaryService.getPid(); 145 // Note that, though this API allows us to request to 146 // kill any process based on its PID, the kernel will 147 // still impose standard restrictions on which PIDs you 148 // are actually able to kill. Typically this means only 149 // the process running your application and any additional 150 // processes created by that app as shown here; packages 151 // sharing a common UID will also be able to kill each 152 // other's processes. 153 Process.killProcess(pid); 154 mCallbackText.setText("Killed service process."); 155 } catch (RemoteException ex) { 156 // Recover gracefully from the process hosting the 157 // server dying. 158 // Just for purposes of the sample, put up a notification. 159 Toast.makeText(Binding.this, 160 R.string.remote_call_failed, 161 Toast.LENGTH_SHORT).show(); 162 } 163 } 164 } 165 }; 166 167 // ---------------------------------------------------------------------- 168 // Code showing how to deal with callbacks. 169 // ---------------------------------------------------------------------- 170 171 /** 172 * This implementation is used to receive callbacks from the remote 173 * service. 174 */ 175 private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() { 176 /** 177 * This is called by the remote service regularly to tell us about 178 * new values. Note that IPC calls are dispatched through a thread 179 * pool running in each process, so the code executing here will 180 * NOT be running in our main thread like most other things -- so, 181 * to update the UI, we need to use a Handler to hop over there. 182 */ 183 public void valueChanged(int value) { 184 mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0)); 185 } 186 }; 187 188 private static final int BUMP_MSG = 1; 189 190 private Handler mHandler = new Handler() { 191 @Override public void handleMessage(Message msg) { 192 switch (msg.what) { 193 case BUMP_MSG: 194 mCallbackText.setText("Received from service: " + msg.arg1); 195 break; 196 default: 197 super.handleMessage(msg); 198 } 199 } 200 201 }; 202 }