How can I programmatically get the phone number of the device that is running my android app?
Wouldn't be recommending to use TelephonyManager
as it requires the app to require READ_PHONE_STATE
permission during runtime.
Should be using Google's Play Service for Authentication, and it will able to allow User to select which phoneNumber to use, and handles multiple SIM cards, rather than us trying to guess which one is the primary SIM Card.
implementation "com.google.android.gms:play-services-auth:$play_service_auth_version"
fun main() {
val googleApiClient = GoogleApiClient.Builder(context)
.addApi(Auth.CREDENTIALS_API).build()
val hintRequest = HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build()
val hintPickerIntent = Auth.CredentialsApi.getHintPickerIntent(
googleApiClient, hintRequest
)
startIntentSenderForResult(
hintPickerIntent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_PHONE_NUMBER -> {
if (requestCode == Activity.RESULT_OK) {
val credential = data?.getParcelableExtra(Credential.EXTRA_KEY)
val selectedPhoneNumber = credential?.id
}
}
}
}