Android一次完美的跨進程服務共享實踐

背景

最近須要作這樣一個事情,一個服務來完成多款App的錄音功能,大體有以下邏輯java

  • 服務以lib的形式集成到各個端
  • 當主App存在時,全部其餘App都使用主App的錄音服務
  • 當主App不存在時,其餘App使用自帶錄音服務
  • 有優先級,優先級高的App有絕對的錄音權限,無論其餘App是否在錄音都要暫停,優先處理高優先級的App請求
  • 支持AudioRecord、MediaRecorder兩種錄音方案

爲何要這麼設計?

  • Android系統底層對錄音有限制,同一時間只支持一個進程使用錄音的功能
  • 業務須要,一切事務保證主App的錄音功能
  • 爲了更好的管理錄音狀態,以及多App相互通訊問題

架構圖設計

Architecture

App層

包含公司全部須要集成錄音服務的端,這裏不須要解釋android

Manager層

該層負責Service層的管理,包括:
服務的綁定,解綁,註冊回調,開啓錄音,中止錄音,檢查錄音狀態,檢查服務運行狀態等git

Service層

核心邏輯層,經過AIDL的實現,來知足跨進程通訊,並提供實際的錄音功能。github

目錄一覽

目錄
看代碼目錄的分配,並結合架構圖,咱們來從底層往上層實現一套邏輯安全

IRecorder 接口定義

public interface IRecorder {

    String startRecording(RecorderConfig recorderConfig);

    void stopRecording();

    RecorderState state();

    boolean isRecording();

}

IRecorder 接口實現

class JLMediaRecorder : IRecorder {

    private var mMediaRecorder: MediaRecorder? = null
    private var mState = RecorderState.IDLE

    @Synchronized
    override fun startRecording(recorderConfig: RecorderConfig): String {
        try {
            mMediaRecorder = MediaRecorder()
            mMediaRecorder?.setAudioSource(recorderConfig.audioSource)

            when (recorderConfig.recorderOutFormat) {
                RecorderOutFormat.MPEG_4 -> {
                    mMediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
                    mMediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
                }
                RecorderOutFormat.AMR_WB -> {
                    mMediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB)
                    mMediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB)
                }
                else -> {
                    mMediaRecorder?.reset()
                    mMediaRecorder?.release()
                    mMediaRecorder = null
                    return "MediaRecorder 不支持 AudioFormat.PCM"
                }
            }
        } catch (e: IllegalStateException) {
            mMediaRecorder?.reset()
            mMediaRecorder?.release()
            mMediaRecorder = null
            return "Error initializing media recorder 初始化失敗";
        }
        return try {
            val file = recorderConfig.recorderFile
            file.parentFile.mkdirs()
            file.createNewFile()
            val outputPath: String = file.absolutePath

            mMediaRecorder?.setOutputFile(outputPath)
            mMediaRecorder?.prepare()
            mMediaRecorder?.start()
            mState = RecorderState.RECORDING
            ""
        } catch (e: Exception) {
            mMediaRecorder?.reset()
            mMediaRecorder?.release()
            mMediaRecorder = null
            recorderConfig.recorderFile.delete()
            e.toString()
        }
    }

    override fun isRecording(): Boolean {
        return mState == RecorderState.RECORDING
    }

    @Synchronized
    override fun stopRecording() {
        try {
            if (mState == RecorderState.RECORDING) {
                mMediaRecorder?.stop()
                mMediaRecorder?.reset()
                mMediaRecorder?.release()
            }
        } catch (e: java.lang.IllegalStateException) {
            e.printStackTrace()
        }
        mMediaRecorder = null
        mState = RecorderState.IDLE
    }

    override fun state(): RecorderState {
        return mState
    }

}

這裏須要注意的就是加 @Synchronized 由於多進程同時調用的時候會出現狀態錯亂問題,須要加上才安全。架構

AIDL 接口定義

interface IRecorderService {

    void startRecording(in RecorderConfig recorderConfig);

    void stopRecording(in RecorderConfig recorderConfig);

    boolean isRecording(in RecorderConfig recorderConfig);

    RecorderResult getActiveRecording();

    void registerCallback(IRecorderCallBack callBack);

    void unregisterCallback(IRecorderCallBack callBack);

}

注意點:
自定義參數須要實現Parcelable接口
須要回調的話也是AIDL接口定義app

AIDL 接口回調定義

interface IRecorderCallBack {

    void onStart(in RecorderResult result);

    void onStop(in RecorderResult result);

    void onException(String error,in RecorderResult result);

}

RecorderService 實現

接下來就是功能的核心,跨進程的服務ide

class RecorderService : Service() {

    private var iRecorder: IRecorder? = null
    private var currentRecorderResult: RecorderResult = RecorderResult()
    private var currentWeight: Int = -1

    private val remoteCallbackList: RemoteCallbackList<IRecorderCallBack> = RemoteCallbackList()

    private val mBinder: IRecorderService.Stub = object : IRecorderService.Stub() {

        override fun startRecording(recorderConfig: RecorderConfig) {
            startRecordingInternal(recorderConfig)
        }

        override fun stopRecording(recorderConfig: RecorderConfig) {
            if (recorderConfig.recorderId == currentRecorderResult.recorderId)
                stopRecordingInternal()
            else {
                notifyCallBack {
                    it.onException(
                        "Cannot stop the current recording because the recorderId is not the same as the current recording",
                        currentRecorderResult
                    )
                }
            }
        }

        override fun getActiveRecording(): RecorderResult? {
            return currentRecorderResult
        }

        override fun isRecording(recorderConfig: RecorderConfig?): Boolean {
            return if (recorderConfig?.recorderId == currentRecorderResult.recorderId)
                iRecorder?.isRecording ?: false
            else false
        }

        override fun registerCallback(callBack: IRecorderCallBack) {
            remoteCallbackList.register(callBack)
        }

        override fun unregisterCallback(callBack: IRecorderCallBack) {
            remoteCallbackList.unregister(callBack)
        }

    }

    override fun onBind(intent: Intent?): IBinder? {
        return mBinder
    }


    @Synchronized
    private fun startRecordingInternal(recorderConfig: RecorderConfig) {

        val willStartRecorderResult =
            RecorderResultBuilder.aRecorderResult().withRecorderFile(recorderConfig.recorderFile)
                .withRecorderId(recorderConfig.recorderId).build()

        if (ContextCompat.checkSelfPermission(
                this@RecorderService,
                android.Manifest.permission.RECORD_AUDIO
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            logD("Record audio permission not granted, can't record")
            notifyCallBack {
                it.onException(
                    "Record audio permission not granted, can't record",
                    willStartRecorderResult
                )
            }
            return
        }

        if (ContextCompat.checkSelfPermission(
                this@RecorderService,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            logD("External storage permission not granted, can't save recorded")
            notifyCallBack {
                it.onException(
                    "External storage permission not granted, can't save recorded",
                    willStartRecorderResult
                )
            }
            return
        }

        if (isRecording()) {

            val weight = recorderConfig.weight

            if (weight < currentWeight) {
                logD("Recording with weight greater than in recording")
                notifyCallBack {
                    it.onException(
                        "Recording with weight greater than in recording",
                        willStartRecorderResult
                    )
                }
                return
            }

            if (weight > currentWeight) {
                //只要權重大於當前權重,當即中止當前。
                stopRecordingInternal()
            }

            if (weight == currentWeight) {
                if (recorderConfig.recorderId == currentRecorderResult.recorderId) {
                    notifyCallBack {
                        it.onException(
                            "The same recording cannot be started repeatedly",
                            willStartRecorderResult
                        )
                    }
                    return
                } else {
                    stopRecordingInternal()
                }
            }

            startRecorder(recorderConfig, willStartRecorderResult)

        } else {

            startRecorder(recorderConfig, willStartRecorderResult)

        }

    }

    private fun startRecorder(
        recorderConfig: RecorderConfig,
        willStartRecorderResult: RecorderResult
    ) {
        logD("startRecording result ${willStartRecorderResult.toString()}")

        iRecorder = when (recorderConfig.recorderOutFormat) {
            RecorderOutFormat.MPEG_4, RecorderOutFormat.AMR_WB -> {
                JLMediaRecorder()
            }
            RecorderOutFormat.PCM -> {
                JLAudioRecorder()
            }
        }

        val result = iRecorder?.startRecording(recorderConfig)

        if (!result.isNullOrEmpty()) {
            logD("startRecording result $result")
            notifyCallBack {
                it.onException(result, willStartRecorderResult)
            }
        } else {
            currentWeight = recorderConfig.weight
            notifyCallBack {
                it.onStart(willStartRecorderResult)
            }
            currentRecorderResult = willStartRecorderResult
        }
    }

    private fun isRecording(): Boolean {
        return iRecorder?.isRecording ?: false
    }

    @Synchronized
    private fun stopRecordingInternal() {
        logD("stopRecordingInternal")
        iRecorder?.stopRecording()
        currentWeight = -1
        iRecorder = null
        MediaScannerConnection.scanFile(
            this,
            arrayOf(currentRecorderResult.recorderFile?.absolutePath),
            null,
            null
        )
        notifyCallBack {
            it.onStop(currentRecorderResult)
        }
    }

    private fun notifyCallBack(done: (IRecorderCallBack) -> Unit) {
        val size = remoteCallbackList.beginBroadcast()
        logD("recorded notifyCallBack  size $size")
        (0 until size).forEach {
            done(remoteCallbackList.getBroadcastItem(it))
        }
        remoteCallbackList.finishBroadcast()
    }

}

這裏須要注意的幾點:
由於是跨進程服務,啓動錄音的時候有多是多個app在同一時間啓動,還有可能在一個App錄音的同時,另外一個App調用中止的功能,因此這裏維護好當前currentRecorderResult對象的維護,還有一個currentWeight字段也很重要,這個字段主要是維護優先級的問題,只要有比當前優先級高的指令,就按新的指令操做錄音服務。
notifyCallBack 在合適時候調用AIDL回調,通知App作相應的操做。ui

RecorderManager 實現

step 1
服務註冊,這裏按主App的包名來啓動,全部App都是以這種方式啓動this

fun initialize(context: Context?, serviceConnectState: ((Boolean) -> Unit)? = null) {
       mApplicationContext = context?.applicationContext
       if (!isServiceConnected) {
           this.mServiceConnectState = serviceConnectState
           val serviceIntent = Intent()
           serviceIntent.`package` = "com.julive.recorder"
           serviceIntent.action = "com.julive.audio.service"
           val isCanBind = mApplicationContext?.bindService(
               serviceIntent,
               mConnection,
               Context.BIND_AUTO_CREATE
           ) ?: false
           if (!isCanBind) {
               logE("isCanBind:$isCanBind")
               this.mServiceConnectState?.invoke(false)
               bindSelfService()
           }
       }
   }

isCanBind 是false的狀況,就是未發現主App的狀況,這個時候就須要啓動本身的服務

private fun bindSelfService() {
        val serviceIntent = Intent(mApplicationContext, RecorderService::class.java)
        val isSelfBind =
            mApplicationContext?.bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE)
        logE("isSelfBind:$isSelfBind")
    }

step 2
鏈接成功後

private val mConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mRecorderService = IRecorderService.Stub.asInterface(service)
            mRecorderService?.asBinder()?.linkToDeath(deathRecipient, 0)
            isServiceConnected = true
            mServiceConnectState?.invoke(true)
        }

        override fun onServiceDisconnected(name: ComponentName) {
            isServiceConnected = false
            mRecorderService = null
            logE("onServiceDisconnected:name=$name")
        }
    }

接下來就能夠用mRecorderService 來操做AIDL接口,最終調用RecorderService的實現

//啓動
fun startRecording(recorderConfig: RecorderConfig?) {
        if (recorderConfig != null)
            mRecorderService?.startRecording(recorderConfig)
    }
//暫停
    fun stopRecording(recorderConfig: RecorderConfig?) {
        if (recorderConfig != null)
            mRecorderService?.stopRecording(recorderConfig)
    }
//是否錄音中
    fun isRecording(recorderConfig: RecorderConfig?): Boolean {
        return mRecorderService?.isRecording(recorderConfig) ?: false
    }

這樣一套完成的跨進程通訊就完成了,代碼註釋不多,通過這個流程的代碼展現,應該能明白總體的調用流程。若是有不明白的,歡迎留言區哦。

總結

經過這兩天,對這個AIDL實現的錄音服務,對跨進程的數據處理有了更加深入的認知,這裏面有幾個比較難處理的就是錄音的狀態維護,還有就是優先級的維護,能把這兩點整明白其實也很好處理。不扯了,有問題留言區交流。

歡迎交流:
git 源碼

相關文章
相關標籤/搜索