文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android自定义来电秀实现总结

2023-01-18 12:02

关注

前言

该文章为对工作中部分业务实现的总结,阅读时间:20分钟,版本:Android 6.0 - 9.0 update time 2021年02月03日11:48:55 文章可能存在不足之处,还望评论批评,一起学习进步。

要想实现自定义 来电秀,首先我们先这样 再这样,然后你这样,最后你再这样一下,就可以了,很好实现的,听懂了么?-,-

效果图

TODO

参考文章

来电秀实现

实现思想

注意:因为篇幅问题,博客只会截取部分代码,太长读者很难读下去,Demo已经调试通过,如果有想看源码的可以移步到我的 GitHub项目地址

申请权限

静态权限

  电话应用,会用到很多权限,我这里尽可能多的静态注册了一些权限,如果引入项目中,需要甄别下,代码如下:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <!-- 读取联系人权限 -->
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.DEVICE_POWER" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
    <uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
    <!-- 读写 联系信息 显示联系人名称 -->
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> 
    <uses-permission android:name="android.permission.READ_CALL_LOG" />
    <uses-permission android:name="android.permission.WRITE_CALL_LOG" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.BROADCAST_PACKAGE_ADDED" />
    <uses-permission android:name="android.permission.BROADCAST_PACKAGE_CHANGED" />
    <uses-permission android:name="android.permission.BROADCAST_PACKAGE_INSTALL" />
    <uses-permission android:name="android.permission.BROADCAST_PACKAGE_REPLACED" />
    <uses-permission android:name="android.permission.RESTART_PACKAGES" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!--android 9.0上使用前台服务,需要添加权限-->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />

动态权限

  AndPermission.with(this)
                .runtime()
                .permission(
                        Permission.Group.PHONE,
                        Permission.Group.LOCATION,
                        Permission.Group.CALL_LOG
                )
                .onGranted {
                    Toast.makeText(applicationContext, "权限同意", Toast.LENGTH_SHORT).show()
                }.onDenied {
                    Toast.makeText(applicationContext, "权限拒绝", Toast.LENGTH_SHORT).show()
                }.start()

  上述代码,为自己测试使用的Demo,所以请求权限直接请求分组中的全部权限了,项目中根据需要动态申请部分权限

  虽然我们已经申请了这么多权限,但是为了能够替换系统电话界面成功,还有一部分权限是需要通过弹框来引导用户去 设置中开启的。

# CallerShowPermissionManager.kt

    fun setRingPermission(context: Context): Boolean {
        perArray.clear()
        if (!OpPermissionUtils.checkPermission(context)) {
            //跳转到悬浮窗设置
            toRequestFloatWindPermission(context)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(context)) {
            //准许系统修改
            opWriteSetting(context)
        }
        if (!isAllowed(context)) {
            //后台弹出权限
            openSettings(context)
        }
        if (!notificationListenerEnable(context)) {
            //通知使用权
            gotoNotificationAccessSetting()
        }
        if (perArray.size != 0) {
            context.startActivities(perArray.toTypedArray())
            return false
        } else {
            LogUtils.e("铃声 高级权限全部同意")
            return true
        }
    }

    fun setRingPermission(context: Context): Boolean {
        perArray.clear()
        if (!OpPermissionUtils.checkPermission(context)) {
            //跳转到悬浮窗设置
            toRequestFloatWindPermission(context)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(context)) {
            //准许系统修改
            opWriteSetting(context)
        }
        if (!isAllowed(context)) {
            //后台弹出权限
            openSettings(context)
        }
        if (!notificationListenerEnable(context)) {
            //通知使用权
            gotoNotificationAccessSetting()
        }
        if (perArray.size != 0) {
            context.startActivities(perArray.toTypedArray())
            return false
        } else {
            LogUtils.e("铃声 高级权限全部同意")
            return true
        }
    }

    private fun toRequestFloatWindPermission(context: Context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val clazz: Class<*> = Settings::class.java
                val field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION")
                val intent = Intent(field[null].toString())
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.data = Uri.parse("package:" + context.packageName)
                perArray.add(intent)
                return
            }
            val intent2 = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            context.startActivity(intent2)
            return
        } catch (e: Exception) {
            if (RomUtils.checkIsMeizuRom()) {
                try {
                    val intent = Intent("com.meizu.safe.security.SHOW_APPSEC")
                    intent.putExtra("packageName", context.packageName)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    context.startActivity(intent)
                } catch (e: java.lang.Exception) {
                    LogUtils.e("请在权限管理中打开悬浮窗管理权限")
                }
            }
            LogUtils.e("请在权限管理中打开悬浮窗管理权限")
            return
        }
    }
    
    private fun isLock(context: Context): Boolean {
        if (RomUtils.checkIsMiuiRom()) {
            return MiuiUtils.canShowLockView(context)
        } else if (RomUtils.checkIsVivoRom()) {
            return VivoUtils.getVivoLockStatus(context)
        }
        return true
    }
    
    private fun isAllowed(context: Context): Boolean {
        if (RomUtils.checkIsMiuiRom()) {
            return MiuiUtils.isAllowed(context)
        } else if (RomUtils.checkIsVivoRom()) {
            return VivoUtils.getvivoBgStartActivityPermissionStatus(context)
        }
        return true
    }
    
    private fun openSettings(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.data = Uri.parse("package:${context.packageName}")
                perArray.add(intent)
            } catch (e: java.lang.Exception) {
                LogUtils.e("请在权限管理中打开后台弹出权限")
            }
        } else {
            LogUtils.e("android 6.0以下")
        }
    }
    
    private fun opWriteSetting(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(context)) {
                val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.data = Uri.parse("package:${context.packageName}")
                perArray.add(intent)
            }
        }
    }
    
    private fun gotoNotificationAccessSetting() {
        try {
            val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            perArray.add(intent)
        } catch (e: ActivityNotFoundException) {
            try {
                val intent = Intent()
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                val cn = ComponentName("com.android.settings", "com.android.settings.Settings\$NotificationAccessSettingsActivity");
                intent.component = cn
                intent.putExtra(":settings:show_fragment", "NotificationAccessSettings")
                perArray.add(intent)
            } catch (ex: Exception) {
                LogUtils.e("获取系统通知失败 e : $ex")
            }
        }
    }
// 暂时把重要代码cv出来了一部分,建议下载Demo源码 ,结合博客一起观看

  上述代码 主要罗列了需要引导用户开启部分设置权限的核心代码和方法。

监听电话

  对于监听电话这块,会有很多兼容性的问题,我们这里先使用广播监听 action = android.intent.action.PHONE_STATE 的广播,然后根据状态调用起来悬浮窗。但是测试Android高版本手机 发现 InCallService 会更好的获取到电话状态,所以我这里的处理方案是 两个方案都保存在了代码中,最后通过调用不同的界面来区分。

BroadcastReceiver +悬浮窗显示实现

# AndroidManifest.xml
// 监听电话状态广播 注册
<receiver android:name=".phone.receiver.PhoneStateReceiver">
            <intent-filter android:priority="2147483647">
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter android:priority="2147483647">
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
            <intent-filter android:priority="2147483647">
                <action android:name="android.intent.action.DUAL_PHONE_STATE" />
            </intent-filter>
            <intent-filter android:priority="2147483647">
                <action android:name="android.intent.action.PHONE_STATE_2" />
            </intent-filter>
            <intent-filter android:priority="2147483647">
                <action android:name="com.cootek.smartdialer.action.PHONE_STATE" />
            </intent-filter>
            <intent-filter android:priority="2147483647">
                <action android:name="com.cootek.smartdialer.action.INCOMING_CALL" />
            </intent-filter>
        </receiver>
# PhoneStateReceiver.kt
class PhoneStateReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        context?.let {
            val action = intent?.action
            if (Intent.ACTION_NEW_OUTGOING_CALL == action || TelephonyManager.ACTION_PHONE_STATE_CHANGED == action) {
                try {
                    val manager = it.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                    var state = manager.callState
                    val phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)
                    if (Intent.ACTION_NEW_OUTGOING_CALL.equals(action, true)) {
                        state = 1000
                    }
                    dealWithCallAction(state, phoneNumber)
                } catch (e: Exception) {
                }
            }
        }
    }
    //来去电的几个状态
    private fun dealWithCallAction(state: Int?, phoneNumber: String?) {
        when (state) {
            // 来电状态 - 显示悬浮窗
            TelephonyManager.CALL_STATE_RINGING -> {
                PhoneStateActionImpl.instance.onRinging(phoneNumber)
            }
            // 空闲状态(挂断) - 关闭悬浮窗
            TelephonyManager.CALL_STATE_IDLE -> {
                PhoneStateActionImpl.instance.onHandUp()
            }
            // 摘机状态(接听) - 保持不作操作
            TelephonyManager.CALL_STATE_OFFHOOK -> {
                PhoneStateActionImpl.instance.onPickUp(phoneNumber)
            }
            1000 -> {   //拨打电话广播状态  - 显示悬浮窗
                PhoneStateActionImpl.instance.onCallOut(phoneNumber)
            }
        }
    }
}

获取到广播的信息后 我们就可以着手 悬浮窗的绘制和 初始化工作

# FloatingWindow.kt
private fun initView() {
        windowManager = mContext?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        params = WindowManager.LayoutParams()
        //高版本适配 全面/刘海屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        params.gravity = Gravity.CENTER
        params.width = WindowManager.LayoutParams.MATCH_PARENT
        params.height = WindowManager.LayoutParams.MATCH_PARENT
        params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        params.format = PixelFormat.TRANSLUCENT
        // 设置 Window flag 为系统级弹框 | 覆盖表层
        params.type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        else
            WindowManager.LayoutParams.TYPE_PHONE
        // 去掉FLAG_NOT_FOCUSABLE隐藏输入 全面屏隐藏虚拟物理按钮办法
        params.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION or
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
        params.systemUiVisibility =
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                        View.SYSTEM_UI_FLAG_FULLSCREEN
        val interceptorLayout: FrameLayout = object : FrameLayout(mContext!!) {
            override fun dispatchKeyEvent(event: KeyEvent): Boolean {
                if (event.action == KeyEvent.ACTION_DOWN) {
                    if (event.keyCode == KeyEvent.KEYCODE_BACK) {
                        return true
                    }
                }
                return super.dispatchKeyEvent(event)
            }
        }
        phoneCallView = LayoutInflater.from(mContext).inflate(R.layout.view_phone_call, interceptorLayout)
        tvCallNumber = phoneCallView.findViewById(R.id.tv_call_number)
        tvPhoneHangUp = phoneCallView.findViewById(R.id.tv_phone_hang_up)
        tvPhonePickUp = phoneCallView.findViewById(R.id.tv_phone_pick_up)
        tvCallingTime = phoneCallView.findViewById(R.id.tv_phone_calling_time)
        tvCallRemark = phoneCallView.findViewById(R.id.tv_call_remark)
    }
... 
// 部分代码省略

  悬浮窗展示完成后,就要设置电话接通和挂断的操作(注意:这里很多低版本手机存在兼容问题,所以会有一些代码比较奇怪)

# IPhoneCallListenerImpl.kt
override fun onAnswer() {
        val mContext = App.context
        try {
            val intent = Intent(mContext, ForegroundActivity::class.java)
            intent.action = CallListenerService.ACTION_PHONE_CALL
            intent.putExtra(CallListenerService.PHONE_CALL_ANSWER, "0")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            mContext.startActivity(intent)
        } catch (e: Exception) {
            Log.e("ymc","startForegroundActivity exception>>$e")
            PhoneCallUtil.answer()
        }
    }
    override fun onOpenSpeaker() {
        PhoneCallUtil.openSpeaker()
    }
    override fun onDisconnect() {
        Log.e("ymc"," onDisconnect")
        val mContext = App.context
        try {
            val intent = Intent(mContext, ForegroundActivity::class.java)
            intent.action = CallListenerService.ACTION_PHONE_CALL
            intent.putExtra(CallListenerService.PHONE_CALL_DISCONNECT, "0")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            mContext.startActivity(intent)
        } catch (e: Exception) {
            Log.e("ymc","startForegroundActivity exception>>$e")
            PhoneCallUtil.disconnect()
        }
    }

  以上代码为接口实现类,我们这里会跳转到 一个前台Activity(一定程度上可以将App拉活),主要逻辑我们放在自己的前台Service中操作。

# CallListenerService.kt
// Andorid新版本 启动服务的方式
fun forceForeground(intent: Intent) {
        try {
            ContextCompat.startForegroundService(App.context, intent)
            notification = CustomNotifyManager.instance?.getNotifyNotification(App.context)
            if (notification != null) {
                startForeground(CustomNotifyManager.STEP_COUNT_NOTIFY_ID, notification)
            } else {
                startForeground(CustomNotifyManager.STEP_COUNT_NOTIFY_ID,
                        CustomNotifyManager.instance?.getDefaultNotification(NotificationCompat.Builder(App.context)))
            }
        } catch (e: Exception) {
        }
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            return START_STICKY
        }
        val action = intent.action ?: return START_STICKY
        when (action) {
            ACTION_PHONE_CALL -> {
                dispatchAction(intent)
            }
        }
        return START_STICKY
    }
private fun dispatchAction(intent: Intent) {
        if (intent.hasExtra(PHONE_CALL_DISCONNECT)) {
            PhoneCallUtil.disconnect()
            return
        }
        if (intent.hasExtra(PHONE_CALL_ANSWER)) {
            PhoneCallUtil.answer()
        }
    }

  为保证我们的服务能够正常吊起来,吊起前台服务,并设置Service等级,代码如下:

# AndroidManifest.xml
<!-- 电话状态接收广播 -->
        <service
            android:name=".phone.service.CallListenerService"
            android:enabled="true"
            android:exported="false">
            <intent-filter android:priority="1000">
                <action android:name="com.maiya.call.phone.service.CallListenerService" />
            </intent-filter>
        </service>
<!-- 监听通知栏权限 必备 -->
<service
            android:name=".phone.service.NotificationService"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>

   低版本的接通和挂断电话,因为需要兼容部分机型,所以我们会有比较多的判断,代码如下:

# PhoneCallUtil.kt

    fun answer() {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
                val telecomManager = App.context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
                if (ActivityCompat.checkSelfPermission(App.context, Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) {
                    return
                }
                telecomManager.acceptRingingCall()
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {
                finalAnswer()
            }
            else -> {
                try {
                    val method: Method = Class.forName("android.os.ServiceManager")
                            .getMethod("getService", String::class.java)
                    val binder = method.invoke(null, Context.TELEPHONY_SERVICE) as IBinder
                    val telephony = ITelephony.Stub.asInterface(binder)
                    telephony.answerRingingCall()
                } catch (e: Exception) {
                    finalAnswer()
                }
            }
        }
    }
    private fun finalAnswer() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val mediaSessionManager = App.context.getSystemService("media_session") as MediaSessionManager
                val activeSessions = mediaSessionManager.getActiveSessions(ComponentName(App.context, NotificationService::class.java)) as List<MediaController>
                if (activeSessions.isNotEmpty()) {
                    for (mediaController in activeSessions) {
                        if ("com.android.server.telecom" == mediaController.packageName) {
                            mediaController.dispatchMediaButtonEvent(KeyEvent(0, 79))
                            mediaController.dispatchMediaButtonEvent(KeyEvent(1, 79))
                            break
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            answerPhoneAidl()
        }
    }
    private fun answerPhoneAidl() {
        try {
            val keyEvent = KeyEvent(0, 79)
            val keyEvent2 = KeyEvent(1, 79)
            if (Build.VERSION.SDK_INT >= 19) {
                @SuppressLint("WrongConstant") val audioManager = App.context.getSystemService("audio") as AudioManager
                audioManager.dispatchMediaKeyEvent(keyEvent)
                audioManager.dispatchMediaKeyEvent(keyEvent2)
            }
        } catch (ex: java.lang.Exception) {
            val intent = Intent("android.intent.action.MEDIA_BUTTON")
            intent.putExtra("android.intent.extra.KEY_EVENT", KeyEvent(0, 79) as Parcelable)
            App.context.sendOrderedBroadcast(intent, "android.permission.CALL_PRIVILEGED")
            val intent2 = Intent("android.intent.action.MEDIA_BUTTON")
            intent2.putExtra("android.intent.extra.KEY_EVENT", KeyEvent(1, 79) as Parcelable)
            App.context.sendOrderedBroadcast(intent2, "android.permission.CALL_PRIVILEGED")
        }
    }
    
    fun disconnect() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            with(PhoneCallManager.instance) {
                if (!hasDefaultCall()) {
                    return@with
                }
                mainCallId?.let {
                    val result = disconnect(it)
                    if (result) {
                        return
                    }
                }
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val telecomManager = App.context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
            if (ActivityCompat.checkSelfPermission(App.context, Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) {
                return
            }
            telecomManager.endCall()
        } else {
            try {
                val method: Method = Class.forName("android.os.ServiceManager")
                        .getMethod("getService", String::class.java)
                val binder = method.invoke(null, Context.TELEPHONY_SERVICE) as IBinder
                val telephony = ITelephony.Stub.asInterface(binder)
                telephony.endCall()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

  到这里中低版本的电话接通和挂断,基本已经完毕。下一步 我们主要写,用户在同意设置应用为默认电话应用后的 更加简单方便的实现方式。

InCallService + Activity实现

在使用 InCallService 服务的同时,需要设置该应用为默认拨号应用 (这里只说明技术的可能性,不对用户行为分析)。

# AndroidManifest.xml
<!-- 电话service -->
        <service
            android:name=".phone.service.PhoneCallService"
            android:permission="android.permission.BIND_INCALL_SERVICE">
            <!-- name为自己的Service名字,per和 filter中的name为固定值 -->
            <intent-filter>
                <action android:name="android.telecom.InCallService" />
            </intent-filter>
            <meta-data
                android:name="android.telecom.IN_CALL_SERVICE_UI"
                android:value="true" />
        </service>
# PhoneCallService.kt 
@RequiresApi(Build.VERSION_CODES.M)
class PhoneCallService : InCallService() {
    companion object {
        const val ACTION_SPEAKER_ON = "action_speaker_on"
        const val ACTION_SPEAKER_OFF = "action_speaker_off"
        const val ACTION_MUTE_ON = "action_mute_on"
        const val ACTION_MUTE_OFF = "action_mute_off"
        fun startService(action: String?) {
            val intent = Intent(App.context, PhoneCallService::class.java).apply {
                this.action = action
            }
            App.context.startService(intent)
        }
    }
    // Call 添加 (Call对象需要判断是否有多个呼入的情况)
    override fun onCallAdded(call: Call?) {
        super.onCallAdded(call)
        call?.let {
            it.registerCallback(callback)
            PhoneCallManager.instance.addCall(it)
        }
    }
    // Call 移除 (可以理解为某一个通话的结束)
    override fun onCallRemoved(call: Call?) {
        super.onCallRemoved(call)
        call?.let {
            it.unregisterCallback(callback)
            PhoneCallManager.instance.removeCall(it)
        }
    }
    override fun onCanAddCallChanged(canAddCall: Boolean) {
        super.onCanAddCallChanged(canAddCall)
        PhoneCallManager.instance.onCanAddCallChanged(canAddCall)
    }
    // 将Call CallBack放在PhoneCallManager类中统一处理
    private val callback: Call.Callback = object : Call.Callback() {
        override fun onStateChanged(call: Call?, state: Int) {
            super.onStateChanged(call, state)
            PhoneCallManager.instance.onCallStateChanged(call, state)
        }
        override fun onCallDestroyed(call: Call) {
            call.hold()
            super.onCallDestroyed(call)
        }
    }
    // 设置扬声器
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_SPEAKER_ON -> setAudioRoute(CallAudioState.ROUTE_SPEAKER)
            ACTION_SPEAKER_OFF -> setAudioRoute(CallAudioState.ROUTE_EARPIECE)
            ACTION_MUTE_ON -> setMuted(true)
            ACTION_MUTE_OFF -> setMuted(false)
            else -> {
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }
}

  以上为InCallService的代码。部分方法进行了说明。

# PhoneCallManager.kt

    @RequiresApi(Build.VERSION_CODES.M)
    fun answer(callId: String?) =
            getCallById(callId)?.let {
                it.answer(VideoProfile.STATE_AUDIO_ONLY)
                true
            } ?: false
    
    @RequiresApi(Build.VERSION_CODES.M)
    fun disconnect(callId: String?) =
            getCallById(callId)?.let {
                it.disconnect()
                true
            } ?: false

由于篇幅问题,PhoneCallManager中的代码不全部展示,需要的小伙伴请移步Github,该类中主要进行了一些默认拨号应用,呼叫Call是否保持等一些操作。

以上就是Android 自定义来电秀实现总结的详细内容,更多关于Android 自定义来电秀的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯