源于《Android开发艺术探索》,作者讲的跨进程通信之AIDL。
作者是在同一个moudle下写的aidl,我为了模拟真实情况,所以在两个不同的app下面使用了。
说一些注意的点吧。
首先Aidl支持的类型
.基本数据类型
.String 和CharSequence
.ArrayList
.HashMap
.Parcelable
.AIDL
比如例子中用到了Book。Book实现了Parcelable接口。
并且要为Book专门创建一个Aidl
Book.aidl(创建的时候似乎会提示需要唯一名称,可以先创建其他名称然后重命名)
package com.example.lps.aidlserver;
parcelable Book;
然后就是接口什么的,
package com.example.lps.aidlserver;
import com.example.lps.aidlserver.Book;
import com.example.lps.aidlserver.IOnNewBookArrivedListener;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
List<Book> getBookList();
void addBook(in Book book);
void regisiterListener(IOnNewBookArrivedListener listener);
void unregisiterListener(IOnNewBookArrivedListener listener);
}
然后编译一下就会在
image.png这里生成代码。
然后服务端创建Service
package com.example.lps.aidlserver;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by lps on 2017/7/3.
*
* @version 1
* @see
* @since 2017/7/3 17:11
*/
public class BookManagerService extends Service {
@Override
public void onCreate() {
super.onCreate();
mBookList.add(new Book("Android开发艺术探索", "任玉刚"));
mBookList.add(new Book("Android高级进阶", "未知"));
mBookList.add(new Book("疯狂android讲义", "李刚"));
new Thread(new ServiceWorker()).start();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private static final String TAG = "BookManagerService";
private AtomicBoolean mIsServiceDestroyed = new AtomicBoolean(false);
private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<>();
private RemoteCallbackList<IOnNewBookArrivedListener> mRemoteCallbackList=new RemoteCallbackList<>();
private CopyOnWriteArrayList<IOnNewBookArrivedListener> mIOnNewBookArrivedListeners = new CopyOnWriteArrayList<>();
private Binder mBinder = new IMyAidlInterface.Stub() {
@Override
public List<Book> getBookList() throws RemoteException {
return mBookList;
}
@Override
public void addBook(Book book) throws RemoteException {
mBookList.add(book);
}
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
int mPermission = checkCallingOrSelfPermission("com.example.lps.aidlserver.permission.ACCESS_BOOK_SERVICE");
if (mPermission== PackageManager.PERMISSION_DENIED){//权限验证(似乎一直返回的-1)
return false;
}
String packname=null;
String[] mPackagesForUid = getPackageManager().getPackagesForUid(getCallingUid());
if (mPackagesForUid!=null&&mPackagesForUid.length>0){
packname = mPackagesForUid[0];
}
if (!packname.startsWith("com.example")){
return false;
}
return super.onTransact(code, data, reply, flags);
}
@Override
public void regisiterListener(IOnNewBookArrivedListener listener) throws RemoteException {
// if (!mIOnNewBookArrivedListeners.contains(listener)) {
// mIOnNewBookArrivedListeners.add(listener);
// } else {
// throw new RemoteException(" listener already exists");
// }
mRemoteCallbackList.register(listener);
}
@Override
public void unregisiterListener(IOnNewBookArrivedListener listener) throws RemoteException {
// if (mIOnNewBookArrivedListeners.contains(listener))//false
// mIOnNewBookArrivedListeners.remove(listener);
mRemoteCallbackList.unregister(listener);
}
};
private class ServiceWorker implements Runnable {
@Override
public void run() {
while (!mIsServiceDestroyed.get()) {
try {
Thread.sleep(5000);
} catch (InterruptedException mE) {
mE.printStackTrace();
}
int bookId = mBookList.size() + 1;
Book newBook = new Book("newbook" + bookId, bookId + "");
try {
onNewBookArrived(newBook);
} catch (RemoteException mE) {
mE.printStackTrace();
}
}
}
}
private void onNewBookArrived(Book mNewBook) throws RemoteException {
mBookList.add(mNewBook);
// for (int i = 0; i < mIOnNewBookArrivedListeners.size(); i++) {
// mIOnNewBookArrivedListeners.get(i).onNewBookArrived(mNewBook);
// }
int mBroadcast = mRemoteCallbackList.beginBroadcast();
for (int i = 0; i < mBroadcast; i++) {
IOnNewBookArrivedListener mBroadcastItem = mRemoteCallbackList.getBroadcastItem(i);
if (mBroadcastItem!=null){
mBroadcastItem.onNewBookArrived(mNewBook);
}
}
mRemoteCallbackList.finishBroadcast();
}
}
在吧app作为client端
app需要拷贝aidl相关的东西。并且编译一下生成同样的代码。
代码大致如下
private static final String TAG = "MainActivity";
IMyAidlInterface mAidlInterface;
IOnNewBookArrivedListener mIOnNewBookArrivedListener=new IOnNewBookArrivedListener.Stub() {
@Override
public void onNewBookArrived(Book newBook) throws RemoteException {
Log.e(TAG, "onNewBookArrived() called with: newBook = [" + newBook + "]");
}
};
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAidlInterface = IMyAidlInterface.Stub.asInterface(service);
try {
List<Book> mBookList = mAidlInterface.getBookList();
Log.e(TAG, "onServiceConnected() called with: name = [" + name + "], service = [" + service + "]");
Log.e(TAG, "onServiceConnected: mbooklist" + mBookList);
Book newBook = new Book("从你的全世界路过", "张嘉jia");
mAidlInterface.addBook(newBook);
List<Book> mnewBooklist = mAidlInterface.getBookList();
Log.e(TAG, "onServiceConnected: mnewBooklist" + mnewBooklist);
mAidlInterface.regisiterListener(mIOnNewBookArrivedListener);
} catch (RemoteException mE) {
mE.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent mIntent = new Intent("BookManagerService");
bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mAidlInterface!=null&&mAidlInterface.asBinder().isBinderAlive()){
try {
mAidlInterface.unregisiterListener(mIOnNewBookArrivedListener);
} catch (RemoteException mE) {
mE.printStackTrace();
}
}
unbindService(mConnection);
}
需要注意的是,如作者所说对于IOnNewBookArrivedListener
之前用的CopyOnWriteArrayList存储,进行注册和解除注册。实际收到的不是同一个对象。换为RemoteCallbackList处理。具体都在代码中。
后面作者还提到了权限认证。
在服务端定义permission。客户端注册权限。发现似乎权限不能随意命名。前面需要接包名+permission.权限名。我之前随意命名如(lps.BOOK_SERVICE)在onTransact的checkCallingOrSelfPermission返回始终为-1.认证失败。后面改为com.example.lps.aidlserver.permission.ACCESS_BOOK_SERVICE就可以了。
还有第二种根据包名判断的也在代码里面了。
这样暂且算是AIDL入门吧。
跨进程和BInder确实需要慢慢理解。略深奥。
网友评论