Java Code Examples for android.telephony.TelephonyManager#PHONE_TYPE_CDMA

The following examples show how to use android.telephony.TelephonyManager#PHONE_TYPE_CDMA . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeviceInfo.java    From Android-Commons with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the ISO 3166-1 alpha-2 country code for the current device
 *
 * @param context a context reference
 * @return the lowercase country code or `null` if not available
 */
public static String getCountryISO2(final Context context) {
	try {
		final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		final String simCountry = tm.getSimCountryIso();

		// if the SIM country code is available
		if (simCountry != null && simCountry.length() == 2) {
			return simCountry.toLowerCase(Locale.US);
		}
		// if the device is not 3G (would be unreliable)
		else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
			final String networkCountry = tm.getNetworkCountryIso();

			// if the network country code is available
			if (networkCountry != null && networkCountry.length() == 2) {
				return networkCountry.toLowerCase(Locale.US);
			}
		}
	}
	catch (Exception e) { }

	return null;
}
 
Example 2
Source File: DeviceInfo.java    From shinny-futures-android with GNU General Public License v3.0 6 votes vote down vote up
private String getCountryFromNetwork() {
    try {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
            String country = manager.getNetworkCountryIso();
            if (country != null) {
                return country.toUpperCase(Locale.US);
            }
        }
    } catch (Exception e) {
        // Failed to get country from network
        Diagnostics.getLogger().logError("Failed to get country from network", e);
    }
    return null;
}
 
Example 3
Source File: LocationProvider.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toUpperCase(Locale.US);
        } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toUpperCase(Locale.US);
            }
        }
    } catch (Exception e) {
        // fallthrough
    }
    Locale locale = Locale.getDefault();
    return locale.getCountry();
}
 
Example 4
Source File: TelephonyUtil.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public static String getMccMnc(final Context context) {
  final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  final int configMcc = context.getResources().getConfiguration().mcc;
  final int configMnc = context.getResources().getConfiguration().mnc;
  if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
    Log.w(TAG, "Choosing MCC+MNC info from TelephonyManager.getSimOperator()");
    return tm.getSimOperator();
  } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
    Log.w(TAG, "Choosing MCC+MNC info from TelephonyManager.getNetworkOperator()");
    return tm.getNetworkOperator();
  } else if (configMcc != 0 && configMnc != 0) {
    Log.w(TAG, "Choosing MCC+MNC info from current context's Configuration");
    return String.format("%03d%d",
        configMcc,
        configMnc == Configuration.MNC_ZERO ? 0 : configMnc);
  } else {
    return null;
  }
}
 
Example 5
Source File: Helper.java    From smartcoins-wallet with MIT License 6 votes vote down vote up
/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 *
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
public static String getDeviceCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    } catch (Exception e) {
    }
    return null;
}
 
Example 6
Source File: LocationInfo.java    From batteryhub with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a two letter ISO3166-1 alpha-2 standard country code
 * https://en.wikipedia.org/wiki/ISO_3166-1
 * GetCellLocation returns longitude and latitude
 *
 * @param context Application context
 * @return Two letter country code
 */
public static String getCountryCode(Context context) {
    TelephonyManager telephonyManager =
            (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String cc;
    if (telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
        /// Network location is most accurate
        cc = telephonyManager.getNetworkCountryIso();
        if (cc != null && cc.length() == 2) return cc;
        cc = getCountryCodeFromProperty(context, "gsm.operator.numeric");
        if (cc != null && cc.length() == 2) return cc;
        cc = telephonyManager.getSimCountryIso();
        if (cc != null && cc.length() == 2) return cc;
    } else {
        // Telephony manager is unreliable with CDMA
        cc = getCountryCodeFromProperty(context, "ro.cdma.home.operator.numeric");
        if (cc != null && cc.length() == 2) return cc;
    }
    return "Unknown";
}
 
Example 7
Source File: Phone.java    From batteryhub with Apache License 2.0 6 votes vote down vote up
/**
 * Returns numeric mobile network code.
 *
 * @param context Application context
 * @return 2-3 digit network code
 */
public static String getMnc(final Context context) {
    TelephonyManager telephonyManager =
            (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = telephonyManager.getNetworkOperator();
    if (networkOperator != null && networkOperator.length() >= 5) {
        return networkOperator.substring(3);
    }
    String operatorProperty = "gsm.operator.numeric";
    if (telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
        operatorProperty = "ro.cdma.home.operator.numeric"; // CDMA
    }
    networkOperator = Specifications.getStringFromSystemProperty(context, operatorProperty);
    if (networkOperator != null && networkOperator.length() >= 5) {
        return networkOperator.substring(3);
    }
    return "Unknown";
}
 
Example 8
Source File: TelephonyUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public static String getMccMnc(final Context context) {
  final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  final int configMcc = context.getResources().getConfiguration().mcc;
  final int configMnc = context.getResources().getConfiguration().mnc;
  if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
    Log.i(TAG, "Choosing MCC+MNC info from TelephonyManager.getSimOperator()");
    return tm.getSimOperator();
  } else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
    Log.i(TAG, "Choosing MCC+MNC info from TelephonyManager.getNetworkOperator()");
    return tm.getNetworkOperator();
  } else if (configMcc != 0 && configMnc != 0) {
    Log.i(TAG, "Choosing MCC+MNC info from current context's Configuration");
    return String.format(Locale.ROOT, "%03d%d",
        configMcc,
        configMnc == Configuration.MNC_ZERO ? 0 : configMnc);
  } else {
    return null;
  }
}
 
Example 9
Source File: Phone.java    From batteryhub with Apache License 2.0 6 votes vote down vote up
/**
 * Returns numeric mobile country code.
 *
 * @param context Application context
 * @return 3-digit country code
 */
public static String getMcc(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager)
            context.getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = telephonyManager.getNetworkOperator();
    if (networkOperator != null && networkOperator.length() >= 5) {
        return networkOperator.substring(0, 3);
    }
    String operatorProperty = "gsm.operator.numeric";
    if (telephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
        operatorProperty = "ro.cdma.home.operator.numeric"; // CDMA
    }
    networkOperator = Specifications.getStringFromSystemProperty(context, operatorProperty);
    if (networkOperator != null && networkOperator.length() >= 5) {
        return networkOperator.substring(0, 3);
    }
    return "Unknown";
}
 
Example 10
Source File: Phone.java    From batteryhub with Apache License 2.0 5 votes vote down vote up
public static String getType(Context context) {
    TelephonyManager telManager =
            (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    int phoneType = telManager.getPhoneType();
    switch (phoneType) {
        case TelephonyManager.PHONE_TYPE_CDMA:
            return PHONE_TYPE_CDMA;
        case TelephonyManager.PHONE_TYPE_GSM:
            return PHONE_TYPE_GSM;
        default:
            return PHONE_TYPE_NONE;
    }
}
 
Example 11
Source File: SystemUtil.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available).
 *
 * @return country code or null
 */
@Nullable
public static String getUserCountry() {
	Context context = Application.getAppContext();
	String locale = null;

	final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	final String simCountry = tm.getSimCountryIso();
	if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
		locale = simCountry.toUpperCase(Locale.getDefault());
	}
	else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
		String networkCountry = tm.getNetworkCountryIso();
		if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
			locale = networkCountry.toLowerCase(Locale.getDefault());
		}
	}

	if (locale == null || locale.length() != 2) {
		if (VERSION.SDK_INT >= VERSION_CODES.N) {
			locale = getDefaultLocale24().getCountry();
		}
		else {
			locale = getDefaultLocale23().getCountry();
		}
	}

	return locale;
}
 
Example 12
Source File: PhoneUtils.java    From Mobilyzer with Apache License 2.0 5 votes vote down vote up
/** Returns "GSM", "CDMA". */
private String getTelephonyPhoneType() {
	switch (telephonyManager.getPhoneType()) {
	case TelephonyManager.PHONE_TYPE_CDMA:
		return "CDMA";
	case TelephonyManager.PHONE_TYPE_GSM:
		return "GSM";
	case TelephonyManager.PHONE_TYPE_NONE:
		return "None";
	}
	return "Unknown";
}
 
Example 13
Source File: EasySimMod.java    From easydeviceinfo with Apache License 2.0 5 votes vote down vote up
/**
 * Gets carrier.
 *
 * @return the carrier
 */
public final String getCarrier() {
  String result = null;
  if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
    result = tm.getNetworkOperatorName().toLowerCase(Locale.getDefault());
  }
  return CheckValidityUtil.checkValidData(
      CheckValidityUtil.handleIllegalCharacterInResult(result));
}
 
Example 14
Source File: Util.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
public static String getPhoneTypeName(int phoneType) {
    switch (phoneType) {
        case TelephonyManager.PHONE_TYPE_NONE:
            return "None";
        case TelephonyManager.PHONE_TYPE_GSM:
            return "GSM";
        case TelephonyManager.PHONE_TYPE_CDMA:
            return "CDMA";
        case TelephonyManager.PHONE_TYPE_SIP:
            return "SIP";
        default:
            return "Unknown";
    }
}
 
Example 15
Source File: PhoneSucker.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
private String getCellId() {	
	try {			
		String out = "";
		if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
			final GsmCellLocation gLoc = (GsmCellLocation) tm.getCellLocation();
			out = Integer.toString(gLoc.getCid());
		} else if(tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
			final CdmaCellLocation cLoc = (CdmaCellLocation) tm.getCellLocation();
			out = Integer.toString(cLoc.getBaseStationId());
		}
		return out;
	} catch(NullPointerException e) {
		return null;
	}
}
 
Example 16
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Called from native code to request reference location info
 */
private void requestRefLocation() {
    TelephonyManager phone = (TelephonyManager)
            mContext.getSystemService(Context.TELEPHONY_SERVICE);
    final int phoneType = phone.getPhoneType();
    if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {
        GsmCellLocation gsm_cell = (GsmCellLocation) phone.getCellLocation();
        if ((gsm_cell != null) && (phone.getNetworkOperator() != null)
                && (phone.getNetworkOperator().length() > 3)) {
            int type;
            int mcc = Integer.parseInt(phone.getNetworkOperator().substring(0, 3));
            int mnc = Integer.parseInt(phone.getNetworkOperator().substring(3));
            int networkType = phone.getNetworkType();
            if (networkType == TelephonyManager.NETWORK_TYPE_UMTS
                    || networkType == TelephonyManager.NETWORK_TYPE_HSDPA
                    || networkType == TelephonyManager.NETWORK_TYPE_HSUPA
                    || networkType == TelephonyManager.NETWORK_TYPE_HSPA
                    || networkType == TelephonyManager.NETWORK_TYPE_HSPAP) {
                type = AGPS_REF_LOCATION_TYPE_UMTS_CELLID;
            } else {
                type = AGPS_REF_LOCATION_TYPE_GSM_CELLID;
            }
            native_agps_set_ref_location_cellid(type, mcc, mnc,
                    gsm_cell.getLac(), gsm_cell.getCid());
        } else {
            Log.e(TAG, "Error getting cell location info.");
        }
    } else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
        Log.e(TAG, "CDMA not supported.");
    }
}
 
Example 17
Source File: TraceDeviceInfo.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static String getTelephonyHeader() {
	// Telephony manager can tell us a few things...
	String info = "";

	if (m_telephonyManager != null) {
		try { // getDeviceId() requires android.permission.READ_PHONE_STATE
			info = "<deviceid>" + m_telephonyManager.getDeviceId() + "</deviceid>";
		} catch (Exception e1) {
			DebugTool.logError("Failure getting telephony device ID: " + e1.toString(), e1);
		}

		info = "<pt>";
		switch (m_telephonyManager.getPhoneType()) {
			case TelephonyManager.PHONE_TYPE_NONE:
				info += "NONE";
				break;
			case TelephonyManager.PHONE_TYPE_GSM:
				info += "GSM";
				break;
			case TelephonyManager.PHONE_TYPE_CDMA:
				info += "CDMA";
				break;
			default:
				info += "UNKNOWN";
		} // end-switch

		info += "</pt>" + "<nt>";

		switch (m_telephonyManager.getNetworkType()) {
			case TelephonyManager.NETWORK_TYPE_UNKNOWN:
				info += "UKNOWN";
				break;
			case TelephonyManager.NETWORK_TYPE_GPRS:
				info += "GPRS";
				break;
			case TelephonyManager.NETWORK_TYPE_EDGE:
				info += "EDGE";
				break;
			case TelephonyManager.NETWORK_TYPE_UMTS:
				info += "UMTS";
				break;
			case TelephonyManager.NETWORK_TYPE_HSDPA:
				info += "HSDPA";
				break;
			case TelephonyManager.NETWORK_TYPE_HSUPA:
				info += "HSUPA";
				break;
			case TelephonyManager.NETWORK_TYPE_HSPA:
				info += "HSPA";
				break;
			case TelephonyManager.NETWORK_TYPE_CDMA:
				info += "CDMA";
				break;
			case TelephonyManager.NETWORK_TYPE_EVDO_0:
				info += "EVDO_O";
				break;
			case TelephonyManager.NETWORK_TYPE_EVDO_A:
				info += "EVDO_A";
				break;
			case TelephonyManager.NETWORK_TYPE_1xRTT:
				info += "1xRTT";
				break;
			default:
				info += "UNKNOWN";
				break;
		} // end-switch

		info += "</nt>";
	} // end-if
	return info;
}
 
Example 18
Source File: CellTracker.java    From AIMSICDL with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Description:    Add entries to the "DBi_measure" DB table
 *
 * Issues:
 *                  [ ]
 *
 * Notes:           (a)
 *
 *
 * TODO:  Remove OLD notes below, once we have new ones relevant to our new table
 *
 *  From "locationinfo":
 *
 *      $ sqlite3.exe -header aimsicd.db 'select * from locationinfo;'
 *      _id|Lac|CellID|Net|Lat|Lng|Signal|Connection|Timestamp
 *      1|10401|6828xxx|10|54.67874392|25.28693531|24|[10401,6828320,126]No|Di|HSPA||2015-01-21 20:45:10
 *
 *  From "cellinfo":
 *
 *      $ sqlite3.exe -header aimsicd.db 'select * from cellinfo;'
 *      _id|Lac|CellID|Net|Lat|Lng|Signal|Mcc|Mnc|Accuracy|Speed|Direction|NetworkType|MeasurementTaken|OCID_SUBMITTED|Timestamp
 *      1|10401|6828xxx|10|54.67874392|25.28693531|24|246|2|69.0|0.0|0.0|HSPA|82964|0|2015-01-21 20:45:10
 *
 *  Issues:
 *
 */
public void onLocationChanged(Location loc) {

    DeviceApi18.loadCellInfo(tm, mDevice);

    if (!mDevice.mCell.isValid()) {
        CellLocation cellLocation = tm.getCellLocation();
        if (cellLocation != null) {
            switch (mDevice.getPhoneID()) {

                case TelephonyManager.PHONE_TYPE_NONE:
                case TelephonyManager.PHONE_TYPE_SIP:
                case TelephonyManager.PHONE_TYPE_GSM:
                    GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
                    mDevice.mCell.setCID(gsmCellLocation.getCid()); // CID
                    mDevice.mCell.setLAC(gsmCellLocation.getLac()); // LAC
                    mDevice.mCell.setPSC(gsmCellLocation.getPsc()); // PSC
                    break;

                case TelephonyManager.PHONE_TYPE_CDMA:
                    CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
                    mDevice.mCell.setCID(cdmaCellLocation.getBaseStationId()); // BSID ??
                    mDevice.mCell.setLAC(cdmaCellLocation.getNetworkId());     // NID
                    mDevice.mCell.setSID(cdmaCellLocation.getSystemId());      // SID
                    mDevice.mCell.setMNC(cdmaCellLocation.getSystemId());      // MNC <== BUG!??

                    break;
            }
        }
    }

    if (loc != null &&  (Double.doubleToRawLongBits(loc.getLatitude()) != 0  &&  Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {

        mDevice.mCell.setLon(loc.getLongitude());       // gpsd_lon
        mDevice.mCell.setLat(loc.getLatitude());        // gpsd_lat
        mDevice.mCell.setSpeed(loc.getSpeed());         // speed        // TODO: Remove, we're not using it!
        mDevice.mCell.setAccuracy(loc.getAccuracy());   // gpsd_accu
        mDevice.mCell.setBearing(loc.getBearing());     // -- [deg]??   // TODO: Remove, we're not using it!
        mDevice.setLastLocation(loc);                   //

        // Store last known location in preference
        SharedPreferences.Editor prefsEditor;
        prefsEditor = prefs.edit();
        prefsEditor.putString(context.getString(R.string.data_last_lat_lon),
                String.valueOf(loc.getLatitude()) + ":" + String.valueOf(loc.getLongitude()));
        prefsEditor.apply();

        // This only logs a BTS if we have GPS lock
        // Test: ~~Is correct behaviour? We should consider logging all cells, even without GPS.~~
        //if (mTrackingCell) {
            // This also checks that the lac are cid are not in DB before inserting
            dbHelper.insertBTS(mDevice.mCell);
        //}
    }
}
 
Example 19
Source File: CellTracker.java    From AIMSICDL with GNU General Public License v3.0 4 votes vote down vote up
public void onCellLocationChanged(CellLocation location) {

            checkForNeighbourCount(location);
            compareLac(location);
            refreshDevice();
            mDevice.setNetID(tm);
            mDevice.getNetworkTypeName();

            switch (mDevice.getPhoneID()) {

                case TelephonyManager.PHONE_TYPE_NONE:
                case TelephonyManager.PHONE_TYPE_SIP:
                case TelephonyManager.PHONE_TYPE_GSM:
                    GsmCellLocation gsmCellLocation = (GsmCellLocation) location;
                    if (gsmCellLocation != null) {
                        //TODO @EVA where are we sending this setCellInfo data?

                        //TODO
                        /*@EVA
                            Is it a good idea to dump all cells to db because if we spot a known cell
                            with different lac then this will also be dump to db.

                        */
                        mDevice.setCellInfo(
                                gsmCellLocation.toString() +                // ??
                                mDevice.getDataActivityTypeShort() + "|" +  // No,In,Ou,IO,Do
                                mDevice.getDataStateShort() + "|" +         // Di,Ct,Cd,Su
                                mDevice.getNetworkTypeName() + "|"          // HSPA,LTE etc
                        );

                        mDevice.mCell.setLAC(gsmCellLocation.getLac());     // LAC
                        mDevice.mCell.setCID(gsmCellLocation.getCid());     // CID
                        if (gsmCellLocation.getPsc() != -1) {
                            mDevice.mCell.setPSC(gsmCellLocation.getPsc()); // PSC
                        }

                        /*
                            Add cell if gps is not enabled
                            when gps enabled lat lon will be updated
                            by function below

                         */
                    }
                    break;

                case TelephonyManager.PHONE_TYPE_CDMA:
                    CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) location;
                    if (cdmaCellLocation != null) {
                        mDevice.setCellInfo(
                                cdmaCellLocation.toString() +                       // ??
                                mDevice.getDataActivityTypeShort() + "|" +  // No,In,Ou,IO,Do
                                mDevice.getDataStateShort() + "|" +         // Di,Ct,Cd,Su
                                mDevice.getNetworkTypeName() + "|"          // HSPA,LTE etc
                        );
                        mDevice.mCell.setLAC(cdmaCellLocation.getNetworkId());      // NID
                        mDevice.mCell.setCID(cdmaCellLocation.getBaseStationId());  // BID
                        mDevice.mCell.setSID(cdmaCellLocation.getSystemId());       // SID
                        mDevice.mCell.setMNC(cdmaCellLocation.getSystemId());       // MNC <== BUG!??
                        mDevice.setNetworkName(tm.getNetworkOperatorName());        // ??
                    }
            }

        }
 
Example 20
Source File: MyDialerActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
private void listing20_6() {
  String srvcName = Context.TELEPHONY_SERVICE;
  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName);

  // Listing 20-6: Accessing phone-type and the device’s phone number
  String phoneTypeStr = "unknown";

  int phoneType = telephonyManager.getPhoneType();

  switch (phoneType) {
    case (TelephonyManager.PHONE_TYPE_CDMA):
      phoneTypeStr = "CDMA";
      break;
    case (TelephonyManager.PHONE_TYPE_GSM) :
      phoneTypeStr = "GSM";
      break;
    case (TelephonyManager.PHONE_TYPE_SIP):
      phoneTypeStr = "SIP";
      break;
    case (TelephonyManager.PHONE_TYPE_NONE):
      phoneTypeStr = "None";
      break;
    default: break;
  }

  Log.d(TAG, phoneTypeStr);

  // -- These require READ_PHONE_STATE uses-permission --
  int permission = ActivityCompat.checkSelfPermission(this,
    android.Manifest.permission.READ_PHONE_STATE);
  if (permission == PackageManager.PERMISSION_GRANTED) {

    // Read the IMEI for GSM or MEID for CDMA
    String deviceId = telephonyManager.getDeviceId();

    // Read the software version on the phone (note -- not the SDK version)
    String softwareVersion = telephonyManager.getDeviceSoftwareVersion();

    // Get the phone's number (if available)
    String phoneNumber = telephonyManager.getLine1Number();

    // If permission hasn't been granted, request it.
  } else {
    if (ActivityCompat.shouldShowRequestPermissionRationale(
      this, android.Manifest.permission.READ_PHONE_STATE)) {
      // TODO Display additional rationale for the requested permission.
    }
    ActivityCompat.requestPermissions(this,
      new String[]{android.Manifest.permission.READ_PHONE_STATE},
      PHONE_STATE_PERMISSION_REQUEST);
  }
}