Programmatically obtain the phone number of the Android phone

后端 未结 18 1707
南笙
南笙 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:52

    Add this dependency: implementation 'com.google.android.gms:play-services-auth:18.0.0'

    To fetch phone number list use this:

    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()
    
    val intent = Credentials.getClient(context).getHintPickerIntent(hintRequest)
    
    startIntentSenderForResult(
        intent.intentSender,
        PHONE_NUMBER_FETCH_REQUEST_CODE,
        null,
        0,
        0,
        0,
        null
    )
    

    After tap on play services dialog:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent? { 
        super.onActivityResult(requestCode, resultCode, data)
    
        if (requestCode == PHONE_NUMBER_FETCH_REQUEST_CODE) {
            data?.getParcelableExtra(Credential.EXTRA_KEY)?.id?.let { 
                useFetchedPhoneNumber(it)
            }
        }
    }
    

提交回复
热议问题