Programmatically obtain the phone number of the Android phone

后端 未结 18 1700
南笙
南笙 2020-11-21 06:17

How can I programmatically get the phone number of the device that is running my android app?

18条回答
  •  旧巷少年郎
    2020-11-21 06:59

    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
                }
            }
        }
    }
    

提交回复
热议问题