标签(空格分隔): Android开发
Binder实现了IBinder接口,通常我们不会直接去实现Binder,而是通过aidl工具来定义接口,自动生成相应的Binder的子类。
从Android Framework角度来说,Binder是ServiceManager连接各种Manager(ActivityManager,WindowManager,等等)和相应ManagerService的桥梁。
从Android应用层来说,Binder是客户端和服务端进行通信的媒介,通过bindService,服务端会返回一个Binder对象。同过这个Binder对象,客户端就可以获取服务端提供的服务或数据。
我们通过一个简单的AIDL示例来学习Binder的使用。
package com.weijie.aidlapplication.aidl;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by weijie on 17-3-8.
*/
public class Book implements Parcelable {
public int bookId;
public String bookName;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.bookId);
dest.writeString(this.bookName);
}
public Book(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
protected Book(Parcel in) {
this.bookId = in.readInt();
this.bookName = in.readString();
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public Book createFromParcel(Parcel source) {
return new Book(source);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
}
package com.weijie.aidlapplication.aidl;
parcelable Book;
// IBookManager.aidl
package com.weijie.aidlapplication.aidl;
// Declare any non-default types here with import statements
import com.weijie.aidlapplication.aidl.Book;
interface IBookManager {
List getBookList();
void addBook(in Book book);
}
注意:
1. Android Studio中,新建AIDL文件:File->New->AIDL
2. Book.aidl和IBookManager.aidl位于相同的包中,但是在IBookManager中仍然要导入Book类。
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: /home/weijie/AndroidStudioProjects/AidlApplication/app/src/main/aidl/com/weijie/aidlapplication/aidl/IBookManager.aidl
*/
package com.weijie.aidlapplication.aidl;
public interface IBookManager extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.weijie.aidlapplication.aidl.IBookManager
{
private static final java.lang.String DESCRIPTOR = "com.weijie.aidlapplication.aidl.IBookManager";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.weijie.aidlapplication.aidl.IBookManager interface,
* generating a proxy if needed.
*/
public static com.weijie.aidlapplication.aidl.IBookManager asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof com.weijie.aidlapplication.aidl.IBookManager))) {
return ((com.weijie.aidlapplication.aidl.IBookManager)iin);
}
return new com.weijie.aidlapplication.aidl.IBookManager.Stub.Proxy(obj);
}
@Override public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_getBookList:
{
data.enforceInterface(DESCRIPTOR);
java.util.List _result = this.getBookList();
reply.writeNoException();
reply.writeTypedList(_result);
return true;
}
case TRANSACTION_addBook:
{
data.enforceInterface(DESCRIPTOR);
com.weijie.aidlapplication.aidl.Book _arg0;
if ((0!=data.readInt())) {
_arg0 = com.weijie.aidlapplication.aidl.Book.CREATOR.createFromParcel(data);
}
else {
_arg0 = null;
}
this.addBook(_arg0);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.weijie.aidlapplication.aidl.IBookManager
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
@Override public java.util.List getBookList() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.util.List _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getBookList, _data, _reply, 0);
_reply.readException();
_result = _reply.createTypedArrayList(com.weijie.aidlapplication.aidl.Book.CREATOR);
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override public void addBook(com.weijie.aidlapplication.aidl.Book book) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((book!=null)) {
_data.writeInt(1);
book.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_addBook, _data, _reply, 0);
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
}
static final int TRANSACTION_getBookList = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_addBook = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public java.util.List getBookList() throws android.os.RemoteException;
public void addBook(com.weijie.aidlapplication.aidl.Book book) throws android.os.RemoteException;
}
IBookManager包括:
Binder的唯一标示,一般用当前Binder的类名表示。
用于将服务端的Binder对象转换成客户端所需的AIDL接口类型的对象。
这种转换是区分进程的,如果客户端和服务端位于同一进程,那么返回的是服务端的Stub对象本身,否则返回的是系统封装后的Stub.proxy对象。
返回当前的Binder对象
这个方法运行在客户端,它的内部实现是这样的:
这个方法的执行过程和getBookList是一样的,addBook没有返回值,所以它不需要从_reply中取出返回值。
注意:
AIDL支持的数据类型:
如果AIDL文件中用到了自定义的Parcelable对象,那么必须新建一个和它同名的AIDL文件,并在其中声明它为Parcelable类型,如上面的Book.aidl。
AIDL中除了基本数据类型,其它类型的参数必须标上方向:in,out或者inout。
AIDL接口中只支持方法,不支持声明静态常量,这一点区别于传统的接口。
public class BookManagerService extends Service {
private static final String TAG = "BMS";
// CopyOnWriteArrayList支持并发读/写,自动进行线程同步
private CopyOnWriteArrayList mBookList = new CopyOnWriteArrayList();
private Binder mBinder = new IBookManager.Stub() {
@Override
public List getBookList() throws RemoteException {
return mBookList;
}
@Override
public void addBook(Book book) throws RemoteException {
mBookList.add(book);
}
};
public BookManagerService() {
}
@Override
public void onCreate() {
super.onCreate();
mBookList.add(new Book(1, "Android"));
mBookList.add(new Book(2, "Ios"));
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return mBinder;
}
}
虽然服务端返回的是CopyOnWriteArrayList,但是在Binder中会按照List的规范去访问数据并最终形成一个新的ArrayList传递给客户端。
注册BookManagerService
<service
android:name=".aidl.BookManagerService"
android:enabled="true"
android:process=":remote"
android:exported="true">service>
public class MainActivity extends AppCompatActivity {
public static final String TAG = "weijie";
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IBookManager bookManager = IBookManager.Stub.asInterface(service);
List list = bookManager.getBookList();
Log.d(TAG, "onServiceConnected: query book list, list type: " + list.getClass().getCanonicalName());
Log.d(TAG, "onServiceConnected: query book list: " + list.toString());
Book newBook = new Book(3, "Android 开发艺术探索");
Log.d(TAG, "onServiceConnected: add book: " + newBook);
bookManager.addBook(newBook);
List newList = bookManager.getBookList();
Log.d(TAG, "onServiceConnected: query book list: " + newList.toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = new Intent(this, BookManagerService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
}
}
01-02 09:47:15.101 5504 5504 D weijie : onServiceConnected: query book list, list type: java.util.ArrayList
01-02 09:47:15.102 5504 5504 D weijie : onServiceConnected: query book list: [Id = 1, Name = Android, Id = 2, Name = Ios]
01-02 09:47:15.102 5504 5504 D weijie : onServiceConnected: add book: Id = 3, Name = Android 开发艺术探索
01-02 09:47:15.105 5504 5504 D weijie : onServiceConnected: query book list: [Id = 1, Name = Android, Id = 2, Name = Ios, Id = 3, Name = Android 开发艺术探索]
github地址