简体   繁体   中英

How to get user's phone number in Android app?

I searched for getting phone number from Facebook SDK, I come to know that it is not possible. My question is that is there any way by which I can get user phone number from google SDK?

Also how can I get Address information of the user?

The 'Facebook' app for android creates an account in the Android account manager. In case of users who log in(to the FB app) by entering their phone number, you'll be able to get the Facebook registered phone number being saved as the account name.

Go to Settings->Accounts->Facebook

Here, You'll see either of the following 3 ->

1) Email ID used to login to the Facebook App on Android

2) Phone Number used to login to the Facebook App on Android

3) User ID -The unique id for each user. For example Mark Zuckerberg's ID is 'zuck' (from https://www.facebook.com/zuck ).

Now, the trick lies in getting the user to accept the 'contacts' permission. Once you have the 'contacts' permission(don't forget to add the 'accounts' permission also to your manifest) you can use the android.accounts.AccountManager class to access all accounts data(Including Facebook).

AccountManager am = AccountManager.get(this);
    Account[] accounts = am.getAccounts();
    for (Account ac : accounts) {
        String accountType = ac.type;
        if (accountType.equals("com.facebook.auth.login")) {
            String usrDataStr = accountType + "-->" + ac.name;
            Toast.makeText(this, usrDataStr, Toast.LENGTH_LONG).show();
        }
    }

You can use the above code to iterate through the accounts on the android device. The above code basically checks if a Facebook account exists on the device and fetches the associated data.

After a bit of research, I realized that Facebook sets the user's phone number as the account name if he/she entered phone number on the login page. However, if he/she uses email or user-ID, then that is set as the account name.

From my experience, I have noticed that a majority of people tend to login using their phone number. Hence, you have a high probability of getting the user's phone number using this technique.

Hence, this method is good if you're developing an app that's looking for a sneaky way to get a user's contact information (ie, in use cases where getting a phone number is not compulsory). This is not a guaranteed way to get a user's phone number and Facebook might stop exposing such user information once it realizes that this might be a security flaw. Also, the number may belong to another device.

I had reported this issue to Facebook but got a reply from the security team that "this is expected behavior, and it's only used for cross-app communication/not sensitive info".

Check out sample code at : https://github.com/umangmathur92/FacebookVulnerabilityProof

For the 2nd part of the question...

You can get the address of the user by taking the user's location coordinates using the 'FusedLocationApi' of Google play services and then use the result of the location request ie the geographic coordinates to get a list of possible addresses by using the 'Geocoder' class.

1) Inside your onCreate/onCreateView function :

GoogleApiClient mGoogleApiClient = return new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    }
                })
                .addApi(LocationServices.API)
                .build();
            mGoogleApiClient.connect();
                LocationRequest mLocationRequest = new LocationRequest();
                LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
                builder.addLocationRequest(mLocationRequest);
                LocationSettingsRequest mLocationSettingsRequest = builder.build();

                PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, mLocationSettingsRequest);
                result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                    @Override
                    public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                        final Status status = locationSettingsResult.getStatus();
                        switch (status.getStatusCode()) {
                            case LocationSettingsStatusCodes.SUCCESS:
                                Log.i(MY_LOG, "All location settings are satisfied.");
                                getLocation();
                                break;
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                Log.i(MY_LOG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                Log.i(MY_LOG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                                break;
                        }
                    }
                });

2) The 'getLocation' function :

private void getLocation() {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            userProfile.setLatitude(mLastLocation.getLatitude());
            userProfile.setLongitude(mLastLocation.getLongitude());
            AsyncTask<Location, String, List<Address>> reverseGeoCodeTask = getReverseGeoCodeAsyncTask();
            reverseGeoCodeTask.execute(mLastLocation);
        }
    }

3) The Reverse Geocoding AsyncTask :

private AsyncTask<Location, String, List<Address>> getReverseGeoCodeAsyncTask() {
        return new AsyncTask<Location, String, List<Address>>() {

            @Override
            protected List<Address> doInBackground(Location... locations) {
                Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
                try {
                    return geocoder.getFromLocation(locations[0].getLatitude(), locations[0].getLongitude(), 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(List<Address> addresses) {
                super.onPostExecute(addresses);
                if (Utils.notNullOrEmpty(addresses)) {
                    Address address = addresses.get(0);
                    address.getPostalCode();
                    address.getLocality();
                    address.getAdminArea();
                }
            }
        };
    }

Note: I have skipped certain parts of the code which involved permission checks, error handling for the sake of brevity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM