前言
實(shí)現(xiàn)這個(gè)功能要解決兩個(gè)問題:
- 如何使用AIDL進(jìn)行跨進(jìn)程雙向通信?
- 如何傳輸一個(gè)2MB大小的文件?
問題1很簡(jiǎn)單,可以參考AIDL官方文檔,這里不做過多介紹。本文主要集中火力解決問題2,講解如何通過匿名共享內(nèi)存實(shí)現(xiàn)跨進(jìn)程雙向大文件傳輸。
AIDL簡(jiǎn)介
AIDL是Android中實(shí)現(xiàn)跨進(jìn)程通信(Inter-Process Communication)的一種方式。AIDL的傳輸數(shù)據(jù)機(jī)制基于Binder,Binder對(duì)傳輸數(shù)據(jù)大小有限制,
傳輸超過1M的文件就會(huì)報(bào)android.os.TransactionTooLargeException異常,一種解決辦法就是使用匿名共享內(nèi)存進(jìn)行大文件傳輸。

共享內(nèi)存簡(jiǎn)介
共享內(nèi)存是進(jìn)程間通信的一種方式,通過映射一塊公共內(nèi)存到各自的進(jìn)程空間來達(dá)到共享內(nèi)存的目的。

對(duì)于進(jìn)程間需要傳遞大量數(shù)據(jù)的場(chǎng)景下,這種通信方式是十分高效的,但是共享內(nèi)存并未提供同步機(jī)制,也就是說,在第一個(gè)進(jìn)程結(jié)束對(duì)共享內(nèi)存的寫操作之前,并無自動(dòng)機(jī)制可以阻止第二個(gè)進(jìn)程開始對(duì)它進(jìn)行讀取,所以我們通常需要用其他的機(jī)制來同步對(duì)共享內(nèi)存的訪問,例如信號(hào)量。
Android中的匿名共享內(nèi)存(Ashmem)是基于Linux共享內(nèi)存的,借助Binder+文件描述符(FileDescriptor)實(shí)現(xiàn)了共享內(nèi)存的傳遞。它可以讓多個(gè)進(jìn)程操作同一塊內(nèi)存區(qū)域,并且除了物理內(nèi)存限制,沒有其他大小限制。相對(duì)于Linux的共享內(nèi)存,Ashmem對(duì)內(nèi)存的管理更加精細(xì)化,并且添加了互斥鎖。Java層在使用時(shí)需要用到MemoryFile,它封裝了native代碼。Android平臺(tái)上共享內(nèi)存通常的做法如下:
- 進(jìn)程A通過
MemoryFile創(chuàng)建共享內(nèi)存,得到fd(FileDescriptor) - 進(jìn)程A通過fd將數(shù)據(jù)寫入共享內(nèi)存
- 進(jìn)程A將fd封裝成實(shí)現(xiàn)
Parcelable接口的ParcelFileDescriptor對(duì)象,通過Binder將ParcelFileDescriptor對(duì)象發(fā)送給進(jìn)程B - 進(jìn)程B獲從
ParcelFileDescriptor對(duì)象中獲取fd,從fd中讀取數(shù)據(jù)
客戶端和服務(wù)端雙向通信+傳輸大文件實(shí)戰(zhàn)
先放上實(shí)現(xiàn)效果圖:

我們先實(shí)現(xiàn)客戶端向服務(wù)端傳輸大文件,然后再實(shí)現(xiàn)服務(wù)端向客戶端傳輸大文件。
定義AIDL接口
//IMyAidlInterface.aidl
interface IMyAidlInterface {
void client2server(in ParcelFileDescriptor pfd);
}
服務(wù)端
- 實(shí)現(xiàn)
IMyAidlInterface接口
//AidlService.kt
class AidlService : Service() {
private val mStub: IMyAidlInterface.Stub = object : IMyAidlInterface.Stub() {
@Throws(RemoteException::class)
override fun sendData(pfd: ParcelFileDescriptor) {
}
}
override fun onBind(intent: Intent): IBinder {
return mStub
}
}
- 接收數(shù)據(jù)
//AidlService.kt
@Throws(RemoteException::class)
override fun sendData(pfd: ParcelFileDescriptor) {
/**
* 從ParcelFileDescriptor中獲取FileDescriptor
*/
val fileDescriptor = pfd.fileDescriptor
/**
* 根據(jù)FileDescriptor構(gòu)建InputStream對(duì)象
*/
val fis = FileInputStream(fileDescriptor)
/**
* 從InputStream中讀取字節(jié)數(shù)組
*/
val data = fis.readBytes()
......
}
客戶端
-
綁定服務(wù)
- 在項(xiàng)目的
src目錄中加入.aidl文件 - 聲明一個(gè)
IMyAidlInterface接口實(shí)例(基于AIDL生成) - 創(chuàng)建
ServiceConnection實(shí)例,實(shí)現(xiàn)android.content.ServiceConnection接口 - 調(diào)用
Context.bindService()綁定服務(wù),傳入ServiceConnection實(shí)例 - 在
onServiceConnected()實(shí)現(xiàn)中,調(diào)用IMyAidlInterface.Stub.asInterface(binder),將返回參數(shù)轉(zhuǎn)換為IMyAidlInterface類型
- 在項(xiàng)目的
//MainActivity.kt
class MainActivity : AppCompatActivity() {
private var mStub: IMyAidlInterface? = null
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
mStub = IMyAidlInterface.Stub.asInterface(binder)
}
override fun onServiceDisconnected(name: ComponentName) {
mStub = null
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button1.setOnClickListener {
bindService()
}
}
private fun bindService() {
if (mStub != null) {
return
}
val intent = Intent("io.github.kongpf8848.aidlserver.AidlService")
intent.setClassName("io.github.kongpf8848.aidlserver","io.github.kongpf8848.aidlserver.AidlService")
try {
val bindSucc = bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
if (bindSucc) {
Toast.makeText(this, "bind ok", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "bind fail", Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onDestroy() {
if(mStub!=null) {
unbindService(serviceConnection)
}
super.onDestroy()
}
}
-
發(fā)送數(shù)據(jù)
- 將發(fā)送文件轉(zhuǎn)換成字節(jié)數(shù)組
ByteArray - 創(chuàng)建
MemoryFile對(duì)象 - 向
MemoryFile對(duì)象中寫入字節(jié)數(shù)組 - 獲取
MemoryFile對(duì)應(yīng)的FileDescriptor - 根據(jù)
FileDescriptor創(chuàng)建ParcelFileDescriptor - 調(diào)用
IPC方法,發(fā)送ParcelFileDescriptor對(duì)象
- 將發(fā)送文件轉(zhuǎn)換成字節(jié)數(shù)組
//MainActivity.kt
private fun sendLargeData() {
if (mStub == null) {
return
}
try {
/**
* 讀取assets目錄下文件
*/
val inputStream = assets.open("large.jpg")
/**
* 將inputStream轉(zhuǎn)換成字節(jié)數(shù)組
*/
val byteArray=inputStream.readBytes()
/**
* 創(chuàng)建MemoryFile
*/
val memoryFile=MemoryFile("image", byteArray.size)
/**
* 向MemoryFile中寫入字節(jié)數(shù)組
*/
memoryFile.writeBytes(byteArray, 0, 0, byteArray.size)
/**
* 獲取MemoryFile對(duì)應(yīng)的FileDescriptor
*/
val fd=MemoryFileUtils.getFileDescriptor(memoryFile)
/**
* 根據(jù)FileDescriptor創(chuàng)建ParcelFileDescriptor
*/
val pfd= ParcelFileDescriptor.dup(fd)
/**
* 發(fā)送數(shù)據(jù)
*/
mStub?.client2server(pfd)
} catch (e: IOException) {
e.printStackTrace()
} catch (e: RemoteException) {
e.printStackTrace()
}
}
至此,我們已經(jīng)實(shí)現(xiàn)了客戶端向服務(wù)端傳輸大文件,下面就繼續(xù)實(shí)現(xiàn)服務(wù)端向客戶端傳輸大文件功能。服務(wù)端主動(dòng)給客戶端發(fā)送數(shù)據(jù),客戶端只需要進(jìn)行監(jiān)聽即可。
- 定義監(jiān)聽回調(diào)接口
//ICallbackInterface.aidl
package io.github.kongpf8848.aidlserver;
interface ICallbackInterface {
void server2client(in ParcelFileDescriptor pfd);
}
- 在
IMyAidlInterface.aidl中添加注冊(cè)回調(diào)和反注冊(cè)回調(diào)方法,如下:
//IMyAidlInterface.aidl
import io.github.kongpf8848.aidlserver.ICallbackInterface;
interface IMyAidlInterface {
......
void registerCallback(ICallbackInterface callback);
void unregisterCallback(ICallbackInterface callback);
}
- 服務(wù)端實(shí)現(xiàn)接口方法
//AidlService.kt
private val callbacks=RemoteCallbackList<ICallbackInterface>()
private val mStub: IMyAidlInterface.Stub = object : IMyAidlInterface.Stub() {
......
override fun registerCallback(callback: ICallbackInterface) {
callbacks.register(callback)
}
override fun unregisterCallback(callback: ICallbackInterface) {
callbacks.unregister(callback)
}
}
- 客戶端綁定服務(wù)后注冊(cè)回調(diào)
//MainActivity.kt
private val callback=object: ICallbackInterface.Stub() {
override fun server2client(pfd: ParcelFileDescriptor) {
val fileDescriptor = pfd.fileDescriptor
val fis = FileInputStream(fileDescriptor)
val bytes = fis.readBytes()
if (bytes != null && bytes.isNotEmpty()) {
......
}
}
}
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
mStub = IMyAidlInterface.Stub.asInterface(binder)
mStub?.registerCallback(callback)
}
override fun onServiceDisconnected(name: ComponentName) {
mStub = null
}
}
- 服務(wù)端發(fā)送文件,回調(diào)給客戶端。此處僅貼出核心代碼,如下:
//AidlService.kt
private fun server2client(pfd:ParcelFileDescriptor){
val n=callbacks.beginBroadcast()
for(i in 0 until n){
val callback=callbacks.getBroadcastItem(i);
if (callback!=null){
try {
callback.server2client(pfd)
} catch (e:RemoteException) {
e.printStackTrace()
}
}
}
callbacks.finishBroadcast()
}
至此,我們實(shí)現(xiàn)了客戶端和服務(wù)端雙向通信和傳輸大文件??????
GitHub
本文完整的代碼已經(jīng)上傳GitHub,地址:https://github.com/kongpf8848/aidldemo