How to select a contact address from Whatsapp using Whatsapp's native contact picker?

StackOverflow https://stackoverflow.com/questions/21189815

  •  29-09-2022
  •  | 
  •  

문제

I'm trying to select the Whatsapp address of a contact from my app, but given the fact that my app is a util for Whatsapp I want users to keep engaged with the native way of selecting a contact, that way they won't have to get used to a new way of doing things which is annoying for most of us.

I've done some research and I'm aware of links like Send text to specific contact (whatsapp), Sending message through WhatsApp, and some other questions and answers in the site, but they don't use the Whatsapp's contact picker.

Hope you can help.

도움이 되었습니까?

해결책

After playing around for a long while I realized that we can launch the Whatsapp's contact picker activity and receive the results back, but not in the returned uri (the way Android contact picker does) but as an extra. I've come up with the following solution.

To start the Whatsapp's native contact picker we call the following code from our activity:

Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setPackage("com.whatsapp");
    try{
        startActivityForResult(intent, REQUEST_CODE_PICK_WHATSAPP);
    } catch (Exception e) {
        Toast.makeText(MainActivity.this, R.string.notif_no_whatsapp, Toast.LENGTH_SHORT).show();  //no activity found to handle this intent means whatsapp is not installed
    }

Then, inside activity's onActivityResult(...) method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    switch (requestCode) {
    case REQUEST_CODE_PICK_WHATSAPP:
        if(resultCode == RESULT_OK){
            if(intent.hasExtra("contact")){
                String address = intent.getStringExtra("contact");
                Log.d(TAG, "The selected Whatsapp address is: "+address);
            }
        }
        break;

    default:
        break;
    }
}

Hope it contributes to make more apps that integrate with Whatsapp seamlessly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top