关于特定设备上电话管理器空值检查期间的错误

问题描述 投票:1回答:1

我在检查权限和USIM状态后尝试保存他们的电话号码。

在onCreate()方法中,Initialized全局变量TelephonyManager。

mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

TelephonyManager已初始化,但在特定设备(Galaxy S3)上检查了Null。

// Null value confirmed here even though initialized
if(mTelephonyManager != null) {
    if (mTelephonyManager.getSimState() == TelephonyManager.SIM_STATE_ABSENT 
        || mTelephonyManager.getSimState() == TelephonyManager.SIM_STATE_UNKNOWN) {
        // not USIM
        numFlag = false;
        finish();
    } else if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) 
                != PackageManager.PERMISSION_GRANTED) {
        //Permission Check
        numFlag = false;
        finish();
    } else {
        // For security reasons, test in the following ways
        if (TextUtils.isEmpty(SharedUtil.getInstance().getString(this, "phoneNumber"))) {
            // PhoneNumber Init...
        } else {
            // Data Saved...
        }
    }
}else{
    Toast.makeText(SmartIdActivity.this, "Unable to save phone number.", Toast.LENGTH_LONG).show();
    finish();
}

我错了还是这是一个特殊问题?

android telephonymanager
1个回答
0
投票

当设备上未安装SIM卡时,某些设备将返回null。当您尝试调用以下代码时,某些设备会引发异常:

TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

所以,你需要处理它们。像这样的东西:

private boolean isSimCardAvailable() {
  try {
    TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    if (telMgr == null) return false;
    int simState = telMgr.getSimState();
    switch (simState) {
      case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
      case TelephonyManager.SIM_STATE_PIN_REQUIRED:
      case TelephonyManager.SIM_STATE_PUK_REQUIRED:
      case TelephonyManager.SIM_STATE_READY:
      case TelephonyManager.SIM_STATE_NOT_READY:
        return true;
      case TelephonyManager.SIM_STATE_UNKNOWN:
      case TelephonyManager.SIM_STATE_ABSENT:
        //SIM card state: SIM Card Error, permanently disabled
      case TelephonyManager.SIM_STATE_PERM_DISABLED:
        // SIM card state: SIM Card Error, present but faulty
      case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
        // SIM card state: SIM Card restricted, present but not usable due to
        //carrier restrictions.
      case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
        return false;

      default:
        return false;
    }
  } catch (Exception e) {
    Log.e("TAG", "Exception e = " + e.toString());
    return false;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.