Posted By: Saurabh Pant
It holds value until deprecated!
This is a quick and short post on something for which I banged my head on the wall.
While integrating the Phone Selector Api which so far uses an intent sender to show the phone numbers list with the following code is now deprecated.
try { startIntentSenderForResult(intent.getIntentSender(), RESOLVE_HINT, null, 0, 0, 0,null); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); }
On the other hand, the result that we receive in the callback of activity result is deprecated too.
@Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data);
So what’s the fix?
Well, with new ActivityResult Api it is much more simpler.
Firstly, to open the phone number dialog using Phone Selector Api, follow the code
fun getPhoneHintIntent(activity: FragmentActivity): PendingIntent { val hintRequest = HintRequest.Builder() .setPhoneNumberIdentifierSupported(true) .build() val options = CredentialsOptions.Builder() .forceEnableSaveDialog() .build() return Credentials.getClient(activity, options).getHintPickerIntent(hintRequest) }
And then in your activity/fragment, use this intent as follows
val intent = getPhoneHintIntent(activity as FragmentActivity) try { val launcher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { if (it.resultCode == Activity.RESULT_OK) { val credential: Credential? = it.data?.getParcelableExtra(Credential.EXTRA_KEY) print(credential?.id) } } launcher.launch(IntentSenderRequest.Builder(intent).build()) } catch (e: IntentSender.SendIntentException) { e.printStackTrace() }
Job Offers
Here, the launch() method takes in an IntentSenderRequest object in which we pass our intent object. In the callback, we can extract the credential data.
And that is it. We’re good to use the Phone Selector Api for better user experiences with new ActivityResult Api in Kotlin.
Here is the final result:
Hope it’ll help.
Keep Coding
Cheers!