How to Get Current Sim Card Number in Android

How to get simCard number in Android

Add permission in AndroidManifest.xml

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

and then use this code

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
String TAG = "PhoneActivityTAG";
Activity activity = MainActivity.this;
String wantPermission = Manifest.permission.READ_PHONE_STATE;
private static final int PERMISSION_REQUEST_CODE = 1;
ArrayList<String> _mst=new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (!checkPermission(wantPermission)) {
requestPermission(wantPermission);
} else {

Log.d(TAG, "Phone number: " + getPhone());
_mst = getPhone();

for (String op: _mst) {
Log.i("Device Information", String.valueOf(op));
}
}
}

@TargetApi(Build.VERSION_CODES.O)
private ArrayList<String> getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
return null;
}
ArrayList<String> _lst =new ArrayList<>();
_lst.add(String.valueOf(phoneMgr.getCallState()));
_lst.add("IMEI NUMBER :-"+phoneMgr.getImei());
_lst.add("MOBILE NUMBER :-"+phoneMgr.getLine1Number());
_lst.add("SERIAL NUMBER :-"+phoneMgr.getSimSerialNumber());
_lst.add("SIM OPERATOR NAME :-"+phoneMgr.getSimOperatorName());
_lst.add("MEI NUMBER :-"+phoneMgr.getMeid());
_lst.add("SIM STATE :-"+String.valueOf(phoneMgr.getSimState()));
_lst.add("COUNTRY ISO :-"+phoneMgr.getSimCountryIso());
return _lst;
}

private void requestPermission(String permission){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)){
Toast.makeText(activity, "Phone state permission allows us to get phone number. Please allow it for additional functionality.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(activity, new String[]{permission},PERMISSION_REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Phone number: " + getPhone());
} else {
Toast.makeText(activity,"Permission Denied. We can't get phone number.", Toast.LENGTH_LONG).show();
}
break;
}
}

private boolean checkPermission(String permission){
if (Build.VERSION.SDK_INT >= 23) {
int result = ContextCompat.checkSelfPermission(activity, permission);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
} else {
return true;
}
}
}

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

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();
}
}

How to get the mobile number of current sim card in real device?

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

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

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

How to get the phone number and SIM card slot for the current device, on the callback of onCallAdded?

Use call.getDetails().getAccountHandle() to get PhoneAccountHandle.

Then use TelecomManager.getPhoneAccount() to get PhoneAccount instance.


Permission Manifest.permission.READ_PHONE_NUMBERS is needed for applications targeting API level 31+.


Disclaimer: I am no Android expert, so please do validate my thoughts.


EDIT: So solution for both before API 30 and from API 30 could be as such:

@RequiresApi(Build.VERSION_CODES.M)
fun handleCall(context: Context, call: Call) {
var foundAndSetSimDetails = false
val callDetailsAccountHandle = callDetails.accountHandle
val subscriptionManager = context
.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
val telephonyManager =
context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val telecomManager =
context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
val hasReadPhoneStatePermission =
ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == android.content.pm.PackageManager.PERMISSION_GRANTED
val phoneAccount = telecomManager.getPhoneAccount(callDetailsAccountHandle)
//TODO when targeting API 31, we might need to check for a new permission here, of READ_PHONE_NUMBERS
//find SIM by phone account
if (!foundAndSetSimDetails && phoneAccount != null && hasReadPhoneStatePermission) {
val callCapablePhoneAccounts = telecomManager.callCapablePhoneAccounts
run {
callCapablePhoneAccounts?.forEachIndexed { index, phoneAccountHandle ->
if (phoneAccountHandle != callDetailsAccountHandle)
return@forEachIndexed
if (!phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION))
return@run
//found the sim card index
simName = phoneAccount.label?.toString().orEmpty()
simIndex = index + 1
foundAndSetSimDetails = true
return@run
}
}
}
//find SIM by subscription ID
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && hasReadPhoneStatePermission) {
try {
val callSubscriptionId: Int =
telephonyManager.getSubscriptionId(callDetailsAccountHandle!!)
for (subscriptionInfo: SubscriptionInfo in subscriptionManager.activeSubscriptionInfoList) {
val activeSubscriptionId: Int = subscriptionInfo.subscriptionId
if (activeSubscriptionId == callSubscriptionId) {
setSimDetails(telephonyManager, subscriptionInfo)
foundAndSetSimDetails = true
break
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
//find SIM by phone number
if (!foundAndSetSimDetails && hasReadPhoneStatePermission) {
try {
val simPhoneNumber: String? = phoneAccount?.address?.schemeSpecificPart
if (!simPhoneNumber.isNullOrBlank()) {
for (subscriptionInfo in subscriptionManager.activeSubscriptionInfoList) {
if (simPhoneNumber == subscriptionInfo.number) {
setSimDetails(telephonyManager, subscriptionInfo)
foundAndSetSimDetails = true
break
}
}
if (!foundAndSetSimDetails)
}
} catch (e: Throwable) {
e.printStackTrace()
}
}

private fun setSimDetails(telephonyManager: TelephonyManager, subscriptionInfo: SubscriptionInfo) {
var foundSimName: String? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val telephonyManagerForSubscriptionId =
telephonyManager.createForSubscriptionId(subscriptionInfo.subscriptionId)
foundSimName = telephonyManagerForSubscriptionId.simOperatorName
}
if (foundSimName.isNullOrBlank())
foundSimName = subscriptionInfo.carrierName?.toString()
simName = if (foundSimName.isNullOrBlank())
""
else foundSimName
simIndex = subscriptionInfo.simSlotIndex + 1
}

How to fetch current sim number

It is not guaranteed that getLine1Number() will always return SIM card's number on all devices. Because the availability of number depends on its storage in the SIM card.

If the number is not stored/available in SIM card then the method will return empty string.

In order to get user's phone number, you should send an sms from user's device to your server or device (same as Viber or other app does). And for a good practice make sure it is done with user's acknowledgement.

get phone number from sim card with telephonymanager

Ref: How to get the mobile number of current sim card in real device?

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

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

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

OR

Ref: TelephonyManager give me null

> getLine1Number(); returns whatever is stored on the SIM card's MSISDN,
> which isn't filled by some operators.

In your case i am pretty much sure The MSISDN is unfilled.

You should keep one thing in mind.

getLine1Number() sometimes return with null value or with the phone number originally stored in SIM card.



Related Topics



Leave a reply



Submit