Android Service 基础知识
Android AIDL实现IPC通信
AIDL:Android Interface Definition Language,即Android接口定义语言。
Service跨进程传递数据需要借助AIDL,那么它是如何传递数据通信的呢?
Android进程间通信基于Proxy(代理)与Stub(桩或存根)的设计模式。其中,Proxy将特殊性接口转换成通用性接口,Stub将通用性接口转换成特殊性接口,二者之间的数据转换通过Parcel(打包)进行的,Proxy常作为数据发送代理,通过Parcel将数据打包发送,Stub常作为数据接收桩,解包并解析Parcel Data package。Android进程间通信就是通过这样的 “代理-桩” 的设计模式运作的。
AIDL的工作流程图
一般实现的步骤如下:
在服务端Service
- 创建一个*.aidl文件来定义一个可以被客户端调用的业务接口
- 服务端需要提供一个业务接口的实现类,通常继承Stub类
- 通过Service的onBind()方法返回被绑定的业务对象
在客户端Client
- 客户端通过BindService()方法来绑定一个服务对象(业务对象),如绑定成功会回调ServiceConnection接口方法onServiceConnected()
- OnServiceConnection()方法的其中一个参数是在Service中OnBind()返回的Binder的实例
- 通过在OnServiceConnection()方法中接受Binder的实例来调用Binder中返回Service实例的方法,获得Service的实现
- 通过Service的实例就可以调用Service的的共有方法
服务端代码如下
1.新建一个Book的javaBean并实现序列化
public class Book implements Parcelable {
private String name;
private int price;
public Book() {}
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
protected Book(Parcel in) {
name = in.readString();
price = in.readInt();
}
public static final Creator CREATOR = new Creator() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeInt(price);
}
//用到inout的时候需要用到
public void readFromParcel(Parcel parcel){
this.name = parcel.readString();
this.price = parcel.readInt();
}
//方便打印数据
@Override
public String toString() {
return "name : " + name + " , price : " + price;
}
}
2.在与java同层级下新建aidl文件夹,注意包名要与java包名一致
// Book.aidl
package com.arch.service;
// Declare any non-default types here with import statements
parcelable Book;
3.再新建一个IBookManager的aidl文件,这个要引用Book类
// IBookManager.aidl 注意导包import com.wang.test.aidl.Book;
package com.arch.service;
import com.arch.service.Book;
// Declare any non-default types here with import statements
interface IBookManager {
List getBookList();
void addBook(inout Book book);
}
4.Make Project后实现我们的aidl类
public class IBookManagerImpl extends IBookManager.Stub{
private static final String TAG = "BookManagerImpl";
private List mBookList;
public IBookManagerImpl() {
initData();
}
private void initData(){
mBookList = new ArrayList<>();
mBookList.add(new Book("飘", 54));
mBookList.add(new Book("基督山伯爵", 60));
mBookList.add(new Book("我与地坛", 48));
}
@Override
public List getBookList() throws RemoteException {
return mBookList;
}
@Override
public void addBook(Book book) throws RemoteException {
if (book != null) {
//book.setName("新书的名字 InOut");
mBookList.add(book);
} else {
Log.e(TAG, "接收到了一个空对象 InOut");
}
}
}
5.Service的代码如下
public class MyService extends Service {
private static final String TAG = "MyService";
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind Service success!");
return new IBookManagerImpl();
}
}
客户端代码如下
1.新建与服务端包名相同的Book类com.arch.client.service.Book.java
2.复制服务端的aidl文件夹,Make Project
3.客户端的MainActivity代码如下
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String BIND_SERVICE_ACTION = "android.intent.action.RESPOND_AIDL_MESSAGE";
private IBookManager iBookManager;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
Button btnBindService = findViewById(R.id.bindService);
Button btnAddBook = findViewById(R.id.addBook);
tv = findViewById(R.id.tv);
btnBindService.setOnClickListener(v -> {
Intent serviceIntent = new Intent();
serviceIntent.setAction(BIND_SERVICE_ACTION);
serviceIntent.setComponent(new ComponentName("com.arch.service", "com.arch.service.MyService"));
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
});
btnAddBook.setOnClickListener(v -> {
if (null != iBookManager) {
Book book = new Book("新加的书名", 100);
try {
iBookManager.addBook(book);
setBookData();
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(TAG, "bindService Success");
iBookManager = IBookManager.Stub.asInterface(service);
setBookData();
Toast.makeText(getApplicationContext(), "bindRemoteService Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "bindService Failure");
Toast.makeText(getApplicationContext(), "bindRemoteService Failed", Toast.LENGTH_SHORT).show();
}
};
private void setBookData(){
if(iBookManager==null){
return;
}
try {
StringBuilder builder = new StringBuilder();
for (Book book:iBookManager.getBookList()) {
builder.append(book.getName()).append(" ").append(book.getPrice()).append(" ");
}
tv.setText(builder.toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
客户端和服务端文件结构如下:
整体效果图如下:
参考文章
- https://blog.csdn.net/Allan_Bst/article/details/72811628?spm=1001.2014.3001.5501
- https://juejin.cn/post/6844903781931417614