Android app to get system phone number - android

I'm Trying the following code to get System phone number
TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number();
But it is not working.
In my phone, i use
Settings->About Phone-->Status-Phone Number
is there a simple app i can use ? , I m writing from Turkey. does sim card make a difference ?

Not all telecom carriers store the phone number on the SIM card. The approach you are using only works if the SIM card in the device has the mobile number stored on it.
If you cannot see your phone number in the mobile settings, then it means that it isn't stored on the SIM card. You will have to manually ask the user to enter it into your app if you absolutely need it. There is no other way.

You can try something like this. It works perfectly.
public String getPhoneNumber(Context context) {
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String num = mTelephonyMgr.getLine1Number();
return fillPhoneNumber(num);
}
private String fillPhoneNumber(String num) {
try{
if (num != null && num.length() > 0) {
if (num.length() >= 9) {
num = num.replaceAll("\\D", "");
if (num.substring(0, 1).equals("8")) {
num = "+3" + num;
} else if (num.substring(0, 1).equals("0")) {
num = "+38" + num;
} else if (num.substring(0, 1).equals("3")) {
num = "+" + num;
}
}
return num;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
Note: Not all phones return a phone number.

There is no deterministic way to find the MSISDN. The above approach only works if SIM has stored the MSISDN. Other work around is to retrieve the number from facebook. It also may or may not work.
The only sure shot way is to create account with some SMS gateway provider like http://trumpia.com, then send SMS to the toll free number, and then call the API to retrieve the MSISDN.

Related

Programmatically Get phone number in Android

In my Android application, I need to display phone numbers of the Sim cards which are available in the device.
I tried with the below codes
private String getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
return "";
}
return phoneMgr.getLine1Number();
}
and
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<SubscriptionInfo> subscription = SubscriptionManager.from(getApplicationContext()).getActiveSubscriptionInfoList();
for (int i = 0; i < subscription.size(); i++) {
SubscriptionInfo info = subscription.get(i);
Log.d(TAG, "number " + info.getNumber());
Log.d(TAG, "network name : " + info.getCarrierName());
Log.d(TAG, "country iso " + info.getCountryIso());
}
}
But both are returning null or empty string only.
I have added the manifest permission also.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Could you please help me.
Thanks.
some phone companies not give this permission to get number from sim-card because i was same problem in past projects.
(in the past project i want to send OTP on simcard number user can't type his number. it was for security purpose.)
so some of phone gives you output correct and remains give you output as NULL

Getting the Wrong Mobile Prefix in Android

I am making an app where I will get user's complete phone number from the sim - including the country and mobile prefixes. The phone number I have is 061555555, so when I save it to server it should look like this: +38761555555.
And here is my problem - when I use the code from below I get the following: +387218900032555555, ie. instead of 061 becoming 61, it becomes 218900032. This line number gives the wrong number:
MyPhoneNumber = tMgr.getLine1Number();
I have also tried this and this.
This is my code:
// Get users phone number
private String getMyPhoneNumber() {
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Get the SIM country ISO code
String simCountry = tMgr.getSimCountryIso().toUpperCase();
// Get the operator code of the active SIM (MCC + MNC)
String simOperatorCode = tMgr.getSimOperator();
// Get the name of the SIM operator
String simOperatorName = tMgr.getSimOperatorName();
// Get the SIM’s serial number
String simSerial = tMgr.getSimSerialNumber();
String MyPhoneNumber = "0000000000";
try {
MyPhoneNumber = tMgr.getLine1Number();
} catch (NullPointerException ex) {
}
if (MyPhoneNumber.equals("")) {
MyPhoneNumber = tMgr.getSubscriberId();
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber countryNumberProto = null;
try {
countryNumberProto = phoneUtil.parse(MyPhoneNumber, simCountry);
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
String myPhone = phoneUtil.format(countryNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
// I tried INTERNATIONAL and NATIONAL as well
return myPhone;
}
I think you are parsing "national_number" instead of "country_code". Check your JSON parsing code fields logic
{
"country_code": 41,
"national_number": 446681800
}
https://github.com/googlei18n/libphonenumber
I checked my settings->status and found out my phone number is unknown, and instead of my phone number it displays IMEI, so I guess I will have the user confirm his phone number by entering it manually.

Youtube usage calculation using TrafficStats

Using TrafficStats i was checking the youtube app data usage.In some devices it is working fine but not with many other devices.
I found that from developer site, These statistics may not be available on all platforms. If the statistics are not supported by this device, UNSUPPORTED will be returned.
So in these case how can I get the device app usage ?
I was using
TrafficStats.getUidRxBytes(packageInfo.uid) + TrafficStats.getUidTxBytes(packageInfo.uid);
this is returning -1 everytime.
We can use NetworkStats.
https://developer.android.com/reference/android/app/usage/NetworkStats.html
Please see a sample repo which I got the clue.
https://github.com/RobertZagorski/NetworkStats
We can see a similar stackoverflow question as well.
Getting mobile data usage history using NetworkStatsManager
Then I needed to modify this logic for some particular devices. In these devices the normal method won't return proper usage values. So I modified is as
/*
getting youtube usage for both mobile and wifi.
*/
public long getYoutubeTotalusage(Context context) {
String subId = getSubscriberId(context, ConnectivityManager.TYPE_MOBILE);
//both mobile and wifi usage is calculating. For mobile usage we need subscriberid. For wifi we can give it as empty string value.
return getYoutubeUsage(ConnectivityManager.TYPE_MOBILE, subId) + getYoutubeUsage(ConnectivityManager.TYPE_WIFI, "");
}
private long getYoutubeUsage(int networkType, String subScriberId) {
NetworkStats networkStatsByApp;
long currentYoutubeUsage = 0L;
try {
networkStatsByApp = networkStatsManager.querySummary(networkType, subScriberId, 0, System.currentTimeMillis());
do {
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStatsByApp.getNextBucket(bucket);
if (bucket.getUid() == packageUid) {
//rajeesh : in some devices this is immediately looping twice and the second iteration is returning correct value. So result returning is moved to the end.
currentYoutubeUsage = (bucket.getRxBytes() + bucket.getTxBytes());
}
} while (networkStatsByApp.hasNextBucket());
} catch (RemoteException e) {
e.printStackTrace();
}
return currentYoutubeUsage;
}
private String getSubscriberId(Context context, int networkType) {
if (ConnectivityManager.TYPE_MOBILE == networkType) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId();
}
return "";
}

Dual Sim Android

Is there a way that I can access the other sim in my android? I have an android Cherry Mobile Orbit which is a dual sim android phone. I want to develop an SMS application for my phone, but only the 1st sim will be access. I want to access the other sim, so that when i press enter to send the message, there will be a prompt, that which sim the message will be sent.
I know that it's propreitary, but the phone manufacturer has no feedback about it. Is there any other way? tweaking or something?
I think you can use dex2jar or apktool to reverse those app which runs on dual sim card devices, once you found the related "service manager", "telephony manager",some interface stub, or some key words like "Gemini" you can then use Java Reflection, reflects all of method of this class. Then you can achieve this goal.
This method can be used to select one SIM from 2 SIMs!
//above Android API 22
if (Build.VERSION.SDK_INT > 22) {
//for dual sim mobile
SubscriptionManager localSubscriptionManager = SubscriptionManager.from(this);
if (localSubscriptionManager.getActiveSubscriptionInfoCount() > 1) {
//if there are two sims in dual sim mobile
List localList = localSubscriptionManager.getActiveSubscriptionInfoList();
SubscriptionInfo simInfo = (SubscriptionInfo) localList.get(0);
SubscriptionInfo simInfo1 = (SubscriptionInfo) localList.get(1);
final String sim1 = simInfo.getDisplayName().toString();
final String sim2 = simInfo1.getDisplayName().toString();
}else{
//if there is 1 sim in dual sim mobile
TelephonyManager tManager = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String sim1 = tManager.getNetworkOperatorName();
}
}else{
//below android API 22
TelephonyManager tManager = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String sim1 = tManager.getNetworkOperatorName();
}
Then to send an SMS you can use the below method
public static boolean sendSMS(Context context, String smsText) {
SmsManager smsMan = SmsManager.getDefault();
SharedPreferences prefs = context.getSharedPreferences("uinfo", MODE_PRIVATE);
String sim = prefs.getString("sim", "No name defined");
String simName = prefs.getString("simName", "No name defined");
String toNum = "";
try {
if (Build.VERSION.SDK_INT > 22) {
SubscriptionManager localSubscriptionManager = SubscriptionManager.from(context);
if (localSubscriptionManager.getActiveSubscriptionInfoCount() > 1) {
int simID = Integer.parseInt(sim);
List localList = localSubscriptionManager.getActiveSubscriptionInfoList();
SubscriptionInfo simInfo = (SubscriptionInfo) localList.get(simID);
ArrayList<String> parts = smsMan.divideMessage(smsText);
SmsManager.getSmsManagerForSubscriptionId(simInfo.getSubscriptionId()).sendMultipartTextMessage(toNum, null, parts, null, null);
}else{
ArrayList<String> parts = smsMan.divideMessage(smsText);
smsMan.sendMultipartTextMessage(toNum, null, parts, null, null);
}
return true;
}else{
ArrayList<String> parts = smsMan.divideMessage(smsText);
smsMan.sendMultipartTextMessage(toNum, null, parts, null, null);
}
} catch (Exception e) {
}
return false;
}
Officially right now there is no API to support this, you have to contact the device manufacturer.
Assuming that you are developing the app for your own phone, and you are willing to go through the trouble of finding out the IDs (sim_id) assigned to each of your SIM cards (probably via checking the phone's log outputs, searching for sim_id, which was what I did), you can use the following code to set the default SIM for SMS sending:
int simId = <place desired SIM ID here>;
Intent simIntent = new Intent("android.intent.action.SMS_DEFAULT_SIM");
simIntent.putExtra("simid", simId);
sendBroadcast(simIntent);
Combined with some other UI prompt stuff (for actually 'picking' the preferred SIM), this should do the trick.
I'm not at all sure if this approach would work for you (although the code seems quite 'standard'); I figured it out with trial and error on my Mlais MX28 (with a customized ROM). But it's still worth a shot, I suppose. :)
UPDATE:
Strangely, the solution stopped working unexpectedly after a few updates to the app I was working on. But I came across another way (which seems to be more promising). (I believe this can be extended for other SIM selection scenarios as well, as the settings cache contains entries with names gprs_connection_sim_setting, voice_call_sim_setting, video_call_sim_setting and the like.)
ContentValues val = new ContentValues();
val.put("value", "here goes the preferred SIM ID");
getContentResolver().update(Uri.parse("content://settings/system"), val, "name='sms_sim_setting'", null);
(Unfortunately, this requires the android.permission.WRITE_SETTINGS permission.)

Access SIM card from code, I look for code eamples

I am developing a telephony tests on Android, I passed to work with Eclair.
I wish to know how can I work with sim card from code.
I write tests that testing a sim card on our platform
I has a code that use to work on cap cake and has many errors when transfered to Donut/Eclair. Some apis missing etc. Please help me
I would like to get links for code examples
What apis (relevant to Eclair ) should I use
What import to include at the top of my class
What classes should I use
...
Ilana
What you are looking for is TelephonyManager Class. Using this class you can access many information regarding SIM and Phone Hardware.
// Access IMEI, IMSI
private String imeiNumber = null;
private String imsiNumber = null;
try
{
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if( mTelephonyMgr != null )
{
imeiNumber = mTelephonyMgr.getDeviceId();
imsiNumber = mTelephonyMgr.getSubscriberId();
}
else
{
imeiNumber = null;
}
}
catch ( Exception e )
{
System.out.println ( "IMSI Error : " + e.toString() );
}
Sameway, you can use other method of TelephonyManager class to access other SIM information like getSimCountryIso(), getSimOperator(), getSimOperatorName(), getSimSerialNumber() etc.
Well there is the code android.os.Environment.getExternalStorageDirectory() to access its location and a few more by typing android.os.Environment.
The you should look at the File class here.

Categories

Resources