class MainActivity : ComponentActivity() {
private val permissions = arrayOf(
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.CALL_PHONE
)
private val requestCode = 123
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED
) {
val telecomManager = getSystemService(TelecomManager::class.java)
val defaultDialerPackage = telecomManager?.defaultDialerPackage
// Check if the app is the default dialer
if (packageName != defaultDialerPackage) {
val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER)
intent.putExtra(
TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
packageName
)
startActivity(intent)
}
}
if (!arePermissionsGranted()) {
requestPermissions(permissions, requestCode)
} else {
// Permissions are already granted, register as the default dialer
registerAsDefaultDialer()
}
}
private fun arePermissionsGranted(): Boolean {
val permissionsToRequest = mutableListOf<String>()
for (permission in permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
permissionsToRequest.add(permission)
}
}
if (permissionsToRequest.isNotEmpty()) {
// Request missing permissions
ActivityCompat.requestPermissions(this, permissionsToRequest.toTypedArray(), requestCode)
return false
}
// If all permissions are granted, register as the default dialer
registerAsDefaultDialer()
return permissionsToRequest.isEmpty()
}
private fun registerAsDefaultDialer() {
val telecomManager = getSystemService(Context.TELECOM_SERVICE) as TelecomManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (!packageName.equals(telecomManager.defaultDialerPackage)) {
val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER)
intent.putExtra(
TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
packageName
)
startActivity(intent)
}
} else {
// Prior to Android Q, there is no need to register as the default dialer
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
this.requestCode -> {
if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
// Permissions granted, now register as the default dialer
registerAsDefaultDialer()
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}