android 设置应用为默认电话应用

905 阅读1分钟
//需要设置一个页面来处理电话UI
<activity
    android:name=".phone.view.PhoneCallActivity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:launchMode="singleTask"
    android:screenOrientation="portrait"
    android:exported="true">

    <!-- region provides ongoing call UI -->
    <intent-filter>
        <action android:name="android.intent.action.DIAL" />
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="tel" />
    </intent-filter>
    <!-- endregion -->


    <!-- region provides dial UI -->
    <intent-filter>
        <action android:name="android.intent.action.DIAL" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <!-- endregion -->

</activity>
// 设置默认电话的代码
fun buildSetDefaultPhoneCallAppIntent(): Intent? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        Intent().apply {
            action = TelecomManager.ACTION_CHANGE_DEFAULT_DIALER
            putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, MainApp.context.packageName)
        } else null
}

fun setDefaultPhoneCallApp(activity: FragmentActivity): Boolean {
    // 发起将本应用设为默认电话应用的请求,仅支持 Android M 及以上
    return buildSetDefaultPhoneCallAppIntent()?.let {
        if(it.resolveActivity(activity.packageManager)!=null){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                val rm : RoleManager? = activity.getSystemService(RoleManager::class.java)
                if(rm?.isRoleAvailable(RoleManager.ROLE_DIALER) == true){
                    activity.startActivityForResult(rm.createRequestRoleIntent(RoleManager.ROLE_DIALER),100)
                }
            }else {
                activity.startActivityForResult(it,100)
            }
        }else {
            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            MainApp.context.startActivity(it)
        }
        true
    } ?: false
}
//判断是否是默认电话的应用
fun isDefaultPhoneCallApp(): Boolean {
    val manger = MainApp.context.getSystemService(Context.TELECOM_SERVICE) as? TelecomManager
    if (manger != null && manger.defaultDialerPackage != null) {
        return manger.defaultDialerPackage == MainApp.context.packageName
    }
    return false
}