Example usage for android.telephony TelephonyManager getLine1Number

List of usage examples for android.telephony TelephonyManager getLine1Number

Introduction

In this page you can find the example usage for android.telephony TelephonyManager getLine1Number.

Prototype

@SuppressAutoDoc 
@RequiresPermission(anyOf = { android.Manifest.permission.READ_PHONE_STATE,
        android.Manifest.permission.READ_SMS, android.Manifest.permission.READ_PHONE_NUMBERS })
public String getLine1Number() 

Source Link

Document

Returns the phone number string for line 1, for example, the MSISDN for a GSM phone.

Usage

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc/*from w w  w.  ja v  a  2s.  c o  m*/
 */
public String getProperty(String key, String defaultValue) {
    if (key.equalsIgnoreCase("cn1_push_prefix")) {
        /*if(!checkForPermission(Manifest.permission.READ_PHONE_STATE, "This is required to get notifications")){
        return "";
        }*/
        boolean has = hasAndroidMarket();
        if (has) {
            return "gcm";
        }
        return defaultValue;
    }
    if ("OS".equals(key)) {
        return "Android";
    }
    if ("androidId".equals(key)) {
        return Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    if ("cellId".equals(key)) {
        try {
            if (!checkForPermission(Manifest.permission.READ_PHONE_STATE,
                    "This is required to get the cellId")) {
                return defaultValue;
            }
            String serviceName = Context.TELEPHONY_SERVICE;
            TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(serviceName);
            int cellId = ((GsmCellLocation) telephonyManager.getCellLocation()).getCid();
            return "" + cellId;
        } catch (Throwable t) {
            return defaultValue;
        }
    }
    if ("AppName".equals(key)) {

        final PackageManager pm = getContext().getPackageManager();
        ApplicationInfo ai;
        try {
            ai = pm.getApplicationInfo(getContext().getPackageName(), 0);
        } catch (NameNotFoundException e) {
            ai = null;
        }
        String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : null);
        if (applicationName == null) {
            return defaultValue;
        }
        return applicationName;
    }
    if ("AppVersion".equals(key)) {
        try {
            PackageInfo i = getContext().getPackageManager()
                    .getPackageInfo(getContext().getApplicationInfo().packageName, 0);
            return i.versionName;
        } catch (NameNotFoundException ex) {
            ex.printStackTrace();
        }
        return defaultValue;
    }
    if ("Platform".equals(key)) {
        String p = System.getProperty("platform");
        if (p == null) {
            return defaultValue;
        }
        return p;
    }
    if ("User-Agent".equals(key)) {
        String ua = getUserAgent();
        if (ua == null) {
            return defaultValue;
        }
        return ua;
    }
    if ("OSVer".equals(key)) {
        return "" + android.os.Build.VERSION.RELEASE;
    }
    if ("DeviceName".equals(key)) {
        return "" + android.os.Build.MODEL;
    }
    try {
        if ("IMEI".equals(key) || "UDID".equals(key)) {
            if (!checkForPermission(Manifest.permission.READ_PHONE_STATE,
                    "This is required to get the device ID")) {
                return "";
            }
            TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
            String imei = null;
            if (tm != null && tm.getDeviceId() != null) {
                // for phones or 3g tablets
                imei = tm.getDeviceId();
            } else {
                try {
                    imei = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
                } catch (Throwable t) {
                    com.codename1.io.Log.e(t);
                }
            }
            return imei;
        }
        if ("MSISDN".equals(key)) {
            if (!checkForPermission(Manifest.permission.READ_PHONE_STATE,
                    "This is required to get the device ID")) {
                return "";
            }
            TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getLine1Number();
        }
    } catch (Throwable t) {
        // will be caused by no permissions.
        return defaultValue;
    }

    if (getActivity() != null) {
        android.content.Intent intent = getActivity().getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                String value = extras.getString(key);
                if (value != null) {
                    return value;
                }
            }
        }
    }

    //these keys/values are from the Application Resources (strings values)
    try {
        int id = getContext().getResources().getIdentifier(key, "string",
                getContext().getApplicationInfo().packageName);
        if (id != 0) {
            String val = getContext().getResources().getString(id);
            return val;
        }
    } catch (Exception e) {
    }
    return System.getProperty(key, super.getProperty(key, defaultValue));
}

From source file:org.telegram.ui.PassportActivity.java

private void startPhoneVerification(boolean checkPermissions, final String phone, Runnable finishRunnable,
        ErrorRunnable errorRunnable, final PassportActivityDelegate delegate) {
    TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext
            .getSystemService(Context.TELEPHONY_SERVICE);
    boolean simcardAvailable = tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT
            && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
    boolean allowCall = true;
    if (getParentActivity() != null && Build.VERSION.SDK_INT >= 23 && simcardAvailable) {
        allowCall = getParentActivity()// w w  w .j a  v  a  2 s  .c om
                .checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
        if (checkPermissions) {
            permissionsItems.clear();
            if (!allowCall) {
                permissionsItems.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (!permissionsItems.isEmpty()) {
                if (getParentActivity()
                        .shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                    builder.setMessage(LocaleController.getString("AllowReadCall", R.string.AllowReadCall));
                    permissionsDialog = showDialog(builder.create());
                } else {
                    getParentActivity().requestPermissions(
                            permissionsItems.toArray(new String[permissionsItems.size()]), 6);
                }
                pendingPhone = phone;
                pendingErrorRunnable = errorRunnable;
                pendingFinishRunnable = finishRunnable;
                pendingDelegate = delegate;
                return;
            }
        }
    }
    final TLRPC.TL_account_sendVerifyPhoneCode req = new TLRPC.TL_account_sendVerifyPhoneCode();
    req.phone_number = phone;
    req.settings = new TLRPC.TL_codeSettings();
    req.settings.allow_flashcall = simcardAvailable && allowCall;
    if (Build.VERSION.SDK_INT >= 26) {
        try {
            req.settings.app_hash = SmsManager.getDefault()
                    .createAppSpecificSmsToken(PendingIntent.getBroadcast(ApplicationLoader.applicationContext,
                            0, new Intent(ApplicationLoader.applicationContext, SmsReceiver.class),
                            PendingIntent.FLAG_UPDATE_CURRENT));
        } catch (Throwable e) {
            FileLog.e(e);
        }
    } else {
        req.settings.app_hash = BuildVars.SMS_HASH;
        req.settings.app_hash_persistent = true;
    }
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
            Activity.MODE_PRIVATE);
    if (!TextUtils.isEmpty(req.settings.app_hash)) {
        req.settings.flags |= 8;
        preferences.edit().putString("sms_hash", req.settings.app_hash).commit();
    } else {
        preferences.edit().remove("sms_hash").commit();
    }
    if (req.settings.allow_flashcall) {
        try {
            @SuppressLint("HardwareIds")
            String number = tm.getLine1Number();
            if (!TextUtils.isEmpty(number)) {
                req.settings.current_number = phone.contains(number) || number.contains(phone);
                if (!req.settings.current_number) {
                    req.settings.allow_flashcall = false;
                }
            } else {
                req.settings.current_number = false;
            }
        } catch (Exception e) {
            req.settings.allow_flashcall = false;
            FileLog.e(e);
        }
    }

    ConnectionsManager.getInstance(currentAccount).sendRequest(req,
            (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                if (error == null) {
                    HashMap<String, String> values = new HashMap<>();
                    values.put("phone", phone);
                    PassportActivity activity = new PassportActivity(TYPE_PHONE_VERIFICATION, currentForm,
                            currentPassword, currentType, null, null, null, values, null);
                    activity.currentAccount = currentAccount;
                    activity.saltedPassword = saltedPassword;
                    activity.secureSecret = secureSecret;
                    activity.delegate = delegate;
                    activity.currentPhoneVerification = (TLRPC.TL_auth_sentCode) response;
                    presentFragment(activity, true);
                } else {
                    AlertsCreator.processError(currentAccount, error, PassportActivity.this, req, phone);
                }
            }), ConnectionsManager.RequestFlagFailOnServerErrors);
}