How to get phone number or sim card information use android studio?

我与影子孤独终老i 提交于 2019-12-04 17:02:35
Sagar

There is no reliable way to get the phone number from the SIM card. The TelephonyManager reads the phone number from SIM card but its upto the Telecom operators to add this information in the SIM card.

Most of the Telecom operators don't add this information in SIM card hence its not reliable enough.

There is a way to use Google-Play-Service to get the phone number, but it also doesn't gurantee 100% to return the phone number. You can do it as follows.

Add following dependencies in build.gradle:

dependencies {
    ...
    compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.google.android.gms:play-services-auth:11.6.0'
}

Create two constants in MainActivity.java:

private static final int PHONE_NUMBER_HINT = 100;
private final int PERMISSION_REQ_CODE = 200;

In onclick of your Button add following:

final HintRequest hintRequest =
  new HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build();

try {
  final GoogleApiClient googleApiClient =
    new GoogleApiClient.Builder(MainActivity.this).addApi(Auth.CREDENTIALS_API).build();

  final PendingIntent pendingIntent =
    Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest);

  startIntentSenderForResult(
    pendingIntent.getIntentSender(),
    PHONE_NUMBER_HINT,
    null,
    0,
    0,
    0
  );
} catch (Exception e) {
    e.printStackTrace();
}

Add onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PHONE_NUMBER_HINT && resultCode == RESULT_OK) {
        Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
        final String phoneNumber = credential.getId();
    }
}

This are few methods you can use:

mTelephonyMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);;

String countryiso=mTelephonyMgr.getSimCountryIso();

String simOperator=mTelephonyMgr.getSimOperator();

String  simOperatorName=mTelephonyMgr.getSimOperatorName();

String  simSerialNo=mTelephonyMgr.getSimSerialNumber();

int     simState=mTelephonyMgr.getSimState();

String  subscriberID=mTelephonyMgr.getSubscriberId();

Edit

  String mPhoneNumber = mTelephonyMgr.getLine1Number();

for more,visit here.

This Permission is also necessary.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!