/**
   * Enable the keyguard if the settings are appropriate. Return true if all work that will happen
   * is done; returns false if the caller can wait for the keyguard to be shown.
   */
  private void doKeyguardLocked() {
    boolean bEnableKeyguard = SystemProperties.getBoolean("keyguard.enable", true);
    if (!bEnableKeyguard) return;

    // if another app is disabling us, don't show
    if (!mExternallyEnabled) {
      if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");

      // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
      // for an occasional ugly flicker in this situation:
      // 1) receive a call with the screen on (no keyguard) or make a call
      // 2) screen times out
      // 3) user hits key to turn screen back on
      // instead, we reenable the keyguard when we know the screen is off and the call
      // ends (see the broadcast receiver below)
      // TODO: clean this up when we have better support at the window manager level
      // for apps that wish to be on top of the keyguard
      return;
    }

    // if the keyguard is already showing, don't bother
    if (mKeyguardViewManager.isShowing()) {
      if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
      return;
    }

    // if the setup wizard hasn't run yet, don't show
    final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
    final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
    final IccCard.State state = mUpdateMonitor.getSimState();
    final boolean lockedOrMissing =
        state.isPinLocked()
            || ((state == IccCard.State.ABSENT || state == IccCard.State.PERM_DISABLED)
                && requireSim);

    if (!lockedOrMissing && !provisioned) {
      if (DEBUG)
        Log.d(
            TAG,
            "doKeyguard: not showing because device isn't provisioned"
                + " and the sim is not locked or missing");
      return;
    }

    if (mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
      if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
      return;
    }

    if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
    showLocked();
  }
  private void handleNitzTimeReceived(Parcel p) {
    String nitz = (String) responseString(p);
    // if (RILJ_LOGD) unsljLogRet(RIL_UNSOL_NITZ_TIME_RECEIVED, nitz);

    // has bonus long containing milliseconds since boot that the NITZ
    // time was received
    long nitzReceiveTime = p.readLong();

    Object[] result = new Object[2];

    String fixedNitz = nitz;
    String[] nitzParts = nitz.split(",");
    if (nitzParts.length == 4) {
      // 0=date, 1=time+zone, 2=dst, 3=garbage that confuses GsmServiceStateTracker (so remove it)
      fixedNitz = nitzParts[0] + "," + nitzParts[1] + "," + nitzParts[2] + ",";
    }

    result[0] = fixedNitz;
    result[1] = Long.valueOf(nitzReceiveTime);

    boolean ignoreNitz =
        SystemProperties.getBoolean(TelephonyProperties.PROPERTY_IGNORE_NITZ, false);

    if (ignoreNitz) {
      if (RILJ_LOGD) riljLog("ignoring UNSOL_NITZ_TIME_RECEIVED");
    } else {
      if (mNITZTimeRegistrant != null) {
        mNITZTimeRegistrant.notifyRegistrant(new AsyncResult(null, result, null));
      } else {
        // in case NITZ time registrant isnt registered yet
        mLastNITZTimeInfo = result;
      }
    }
  }
 // Returns the current state of the system property that controls
 // strictmode flashes.  One of:
 //    0: not explicitly set one way or another
 //    1: on
 //    2: off
 private int currentStrictModeActiveIndex() {
   if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
     return 0;
   }
   boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
   return enabled ? 1 : 2;
 }
  /**
   * Some dial strings in GSM are defined to do non-call setup things, such as modify or query
   * supplementary service settings (eg, call forwarding). These are generally referred to as "MMI
   * codes". We look to see if the dial string contains a valid MMI code (potentially with a dial
   * string at the end as well) and return info here.
   *
   * <p>If the dial string contains no MMI code, we return an instance with only "dialingNumber" set
   *
   * <p>Please see flow chart in TS 22.030 6.5.3.2
   */
  static GsmMmiCode newFromDialString(String dialString, GSMPhone phone, UiccCardApplication app) {
    Matcher m;
    GsmMmiCode ret = null;

    if (SystemProperties.getBoolean("ro.config.multimode_cdma", false)) {
      m = sPatternSuppServiceGlobalDev.matcher(dialString);
      if (m.matches()) {
        ret = new GsmMmiCode(phone, app);
        ret.action = makeEmptyNull(m.group(MATCH_GROUP_ACTION));
        String DialCode = makeEmptyNull(m.group(MATCH_GROUP_SERVICE_CODE));
        if (DialCode.equals(SC_GLOBALDEV_VM)) {
          ret.sc = SC_GLOBALDEV_VM;
          ret.dialingNumber = "+1" + phone.getMdn();
          return ret;
        } else if (DialCode.equals(SC_GLOBALDEV_CS)) {
          ret.sc = SC_GLOBALDEV_CS;
          ret.dialingNumber = GLOBALDEV_CS;
          return ret;
        } else if (DialCode.length() >= 3 && DialCode.startsWith(SC_GLOBALDEV_CLIR_INVK)) {
          // Dial "#31#PhoneNum" to invoke CLIR temporarily
          dialString = ACTION_DEACTIVATE + SC_CLIR + ACTION_DEACTIVATE + DialCode.substring(2);
        } else if (DialCode.length() >= 3 && DialCode.startsWith(SC_GLOBALDEV_CLIR_SUPP)) {
          // Dial "*31#PhoneNum" to suppress CLIR temporarily
          dialString = ACTION_ACTIVATE + SC_CLIR + ACTION_DEACTIVATE + DialCode.substring(2);
        }
      }
    }

    m = sPatternSuppService.matcher(dialString);

    // Is this formatted like a standard supplementary service code?
    if (m.matches()) {
      ret = new GsmMmiCode(phone, app);
      ret.poundString = makeEmptyNull(m.group(MATCH_GROUP_POUND_STRING));
      ret.action = makeEmptyNull(m.group(MATCH_GROUP_ACTION));
      ret.sc = makeEmptyNull(m.group(MATCH_GROUP_SERVICE_CODE));
      ret.sia = makeEmptyNull(m.group(MATCH_GROUP_SIA));
      ret.sib = makeEmptyNull(m.group(MATCH_GROUP_SIB));
      ret.sic = makeEmptyNull(m.group(MATCH_GROUP_SIC));
      ret.pwd = makeEmptyNull(m.group(MATCH_GROUP_PWD_CONFIRM));
      ret.dialingNumber = makeEmptyNull(m.group(MATCH_GROUP_DIALING_NUMBER));

    } else if (dialString.endsWith("#")) {
      // TS 22.030 sec 6.5.3.2
      // "Entry of any characters defined in the 3GPP TS 23.038 [8] Default Alphabet
      // (up to the maximum defined in 3GPP TS 24.080 [10]), followed by #SEND".

      ret = new GsmMmiCode(phone, app);
      ret.poundString = dialString;
    } else if (isTwoDigitShortCode(phone.getContext(), dialString)) {
      // Is a country-specific exception to short codes as defined in TS 22.030, 6.5.3.2
      ret = null;
    } else if (isShortCode(dialString, phone)) {
      // this may be a short code, as defined in TS 22.030, 6.5.3.2
      ret = new GsmMmiCode(phone, app);
      ret.dialingNumber = dialString;
    }

    return ret;
  }
 static {
   sInitialized = false;
   if (!SystemProperties.getBoolean("config.disable_renderscript", false)) {
     try {
       Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime");
       Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime");
       sRuntime = get_runtime.invoke(null);
       registerNativeAllocation =
           vm_runtime.getDeclaredMethod("registerNativeAllocation", Integer.TYPE);
       registerNativeFree = vm_runtime.getDeclaredMethod("registerNativeFree", Integer.TYPE);
     } catch (Exception e) {
       Log.e(LOG_TAG, "Error loading GC methods: " + e);
       throw new RSRuntimeException("Error loading GC methods: " + e);
     }
     try {
       System.loadLibrary("rs_jni");
       _nInit();
       sInitialized = true;
       sPointerSize = rsnSystemGetPointerSize();
     } catch (UnsatisfiedLinkError e) {
       Log.e(LOG_TAG, "Error loading RS jni library: " + e);
       throw new RSRuntimeException("Error loading RS jni library: " + e);
     }
   }
 }
 public DisplayManagerService(Context context) {
   super(context);
   mContext = context;
   mHandler = new DisplayManagerHandler(DisplayThread.get().getLooper());
   mUiHandler = UiThread.getHandler();
   mDisplayAdapterListener = new DisplayAdapterListener();
   mSingleDisplayDemoMode = SystemProperties.getBoolean("persist.demo.singledisplay", false);
 }
  @Override
  public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    // Hide lockdown VPN on devices that require IMS authentication
    if (SystemProperties.getBoolean("persist.radio.imsregrequired", false)) {
      menu.findItem(R.id.vpn_lockdown).setVisible(false);
    }
  }
  public DisplayManagerService(Context context, Handler mainHandler, Handler uiHandler) {
    mContext = context;
    mHeadless = SystemProperties.get(SYSTEM_HEADLESS).equals("1");

    mHandler = new DisplayManagerHandler(mainHandler.getLooper());
    mUiHandler = uiHandler;
    mDisplayAdapterListener = new DisplayAdapterListener();
    mSingleDisplayDemoMode = SystemProperties.getBoolean("persist.demo.singledisplay", false);

    mHandler.sendEmptyMessage(MSG_REGISTER_DEFAULT_DISPLAY_ADAPTER);
  }
Example #9
0
  // ***** Class Methods
  public PhoneProxy(Phone phone) {
    mActivePhone = phone;
    mResetModemOnRadioTechnologyChange =
        SystemProperties.getBoolean(TelephonyProperties.PROPERTY_RESET_ON_RADIO_TECH_CHANGE, false);
    mIccSmsInterfaceManagerProxy =
        new IccSmsInterfaceManagerProxy(phone.getIccSmsInterfaceManager());
    mIccPhoneBookInterfaceManagerProxy =
        new IccPhoneBookInterfaceManagerProxy(phone.getIccPhoneBookInterfaceManager());
    mPhoneSubInfoProxy = new PhoneSubInfoProxy(phone.getPhoneSubInfo());
    mCommandsInterface = ((PhoneBase) mActivePhone).mCM;

    mCommandsInterface.registerForRilConnected(this, EVENT_RIL_CONNECTED, null);
    mCommandsInterface.registerForOn(this, EVENT_RADIO_ON, null);
    mCommandsInterface.registerForVoiceRadioTechChanged(this, EVENT_VOICE_RADIO_TECH_CHANGED, null);
  }
Example #10
0
    GlRenderer(int glVersion, boolean translucent) {
      mGlVersion = glVersion;
      mTranslucent = translucent;

      String property;

      property = SystemProperties.get(DISABLE_VSYNC_PROPERTY, "false");
      mVsyncDisabled = "true".equalsIgnoreCase(property);
      if (mVsyncDisabled) {
        Log.d(LOG_TAG, "Disabling v-sync");
      }

      property = SystemProperties.get(PROFILE_PROPERTY, "false");
      mProfileEnabled = "true".equalsIgnoreCase(property);
      if (mProfileEnabled) {
        Log.d(LOG_TAG, "Profiling hardware renderer");
      }

      if (mProfileEnabled) {
        property =
            SystemProperties.get(PROFILE_MAXFRAMES_PROPERTY, Integer.toString(PROFILE_MAX_FRAMES));
        int maxProfileFrames = Integer.valueOf(property);
        mProfileData = new float[maxProfileFrames * PROFILE_FRAME_DATA_COUNT];
        for (int i = 0; i < mProfileData.length; i += PROFILE_FRAME_DATA_COUNT) {
          mProfileData[i] = mProfileData[i + 1] = mProfileData[i + 2] = -1;
        }

        mProfileLock = new ReentrantLock();
      } else {
        mProfileData = null;
        mProfileLock = null;
      }

      property = SystemProperties.get(DEBUG_DIRTY_REGIONS_PROPERTY, "false");
      mDebugDirtyRegions = "true".equalsIgnoreCase(property);
      if (mDebugDirtyRegions) {
        Log.d(LOG_TAG, "Debugging dirty regions");
      }

      mShowOverdraw =
          SystemProperties.getBoolean(HardwareRenderer.DEBUG_SHOW_OVERDRAW_PROPERTY, false);
    }
  public void setFlashlight(boolean enabled) {
    // yinqi, use different node path according to system's property
    Log.d(TAG, "file exists:" + isFileExists(deviceNode2));
    if (android.os.SystemProperties.getBoolean("ro.ledlight.torch", false)
        && isFileExists(deviceNode2)) {
      enableDevice(deviceNode2, enabled ? true : false);
      return;
    }

    if (isTorchNode) {
      enableDevice(deviceNode, enabled ? true : false);
      return;
    }

    if (enabled) {
      mycam = Camera.open();
      if (mycam == null) {
        Log.e(TAG, "Open Camera failed.");
        return;
      }
      camerPara = mycam.getParameters();
      if (camerPara == null) {
        Log.e(TAG, "GetParameters failed.");
        return;
      }
      camerPara.setFlashMode(Parameters.FLASH_MODE_TORCH);
      mycam.setParameters(camerPara);
    } else {
      if (camerPara != null) {
        camerPara.setFlashMode(Parameters.FLASH_MODE_OFF);
      }
      if (mycam != null) {
        mycam.setParameters(camerPara);
        mycam.release();
      }
    }
  }
 /**
  * Helper function for newFromDialString. Returns true if dialString appears to be a short code
  * AND conditions are correct for it to be treated as such.
  */
 private static boolean isShortCode(String dialString, GSMPhone phone) {
   // check for any  Adapt change requirements.
   boolean shortCodeExclusionFlag = false;
   if (SystemProperties.getBoolean("persist.cust.tel.adapt", false)) {
     if (dialString.length() == 2) {
       Log.i(LOG_TAG, "Adapt, Number needs to be checked for short code exclusion list");
       shortCodeExclusionFlag = isExcludedShortCode(dialString);
     }
   }
   // Refer to TS 22.030 Figure 3.5.3.2:
   // A 1 or 2 digit "short code" is treated as USSD if it is entered while on a call or
   // does not satisfy the condition (exactly 2 digits && starts with '1').
   return ((dialString != null && dialString.length() <= 2)
       && !PhoneNumberUtils.isEmergencyNumber(dialString)
       && (phone.isInCall()
           || !((dialString.length() == 2 && dialString.charAt(0) == '1')
               || shortCodeExclusionFlag
               /*
                * While contrary to TS 22.030, there is strong precedence for
                * treating "0" and "00" as call setup strings.
                */
               || dialString.equals("0")
               || dialString.equals("00"))));
 }
  public UsbDeviceManager(Context context, UsbAlsaManager alsaManager) {
    mContext = context;
    mUsbAlsaManager = alsaManager;
    mContentResolver = context.getContentResolver();
    PackageManager pm = mContext.getPackageManager();
    mHasUsbAccessory = pm.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
    initRndisAddress();

    readOemUsbOverrideConfig();

    mHandler = new UsbHandler(FgThread.get().getLooper());

    if (nativeIsStartRequested()) {
      if (DEBUG) Slog.d(TAG, "accessory attached at boot");
      startAccessoryMode();
    }

    boolean secureAdbEnabled = SystemProperties.getBoolean("ro.adb.secure", false);
    boolean dataEncrypted = "1".equals(SystemProperties.get("vold.decrypt"));
    if (secureAdbEnabled && !dataEncrypted) {
      mDebuggingManager = new UsbDebuggingManager(context);
    }
    mContext.registerReceiver(mHostReceiver, new IntentFilter(UsbManager.ACTION_USB_PORT_CHANGED));
  }
 private void updateDebugLayoutOptions() {
   updateCheckBox(mDebugLayout, SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
 }
Example #15
0
 boolean isProvisioningNeeded() {
   if (SystemProperties.getBoolean("net.tethering.noprovisioning", false)) {
     return false;
   }
   return mProvisionApp.length == 2;
 }
  /**
   * Handles RIL_UNSOL_STK_EVENT_NOTIFY or RIL_UNSOL_STK_PROACTIVE_COMMAND command from RIL. Sends
   * valid proactive command data to the application using intents.
   * RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE will be send back if the command is from
   * RIL_UNSOL_STK_PROACTIVE_COMMAND.
   */
  private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) {
    CatLog.d(this, cmdParams.getCommandType().name());

    CharSequence message;
    CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams);
    switch (cmdParams.getCommandType()) {
      case SET_UP_MENU:
        if (removeMenu(cmdMsg.getMenu())) {
          mMenuCmd = null;
        } else {
          mMenuCmd = cmdMsg;
        }
        sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
        break;
      case DISPLAY_TEXT:
        // when application is not required to respond, send an immediate response.
        if (!cmdMsg.geTextMessage().responseNeeded) {
          sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
        }
        break;
      case REFRESH:
        // ME side only handles refresh commands which meant to remove IDLE
        // MODE TEXT.
        cmdParams.cmdDet.typeOfCommand = CommandType.SET_UP_IDLE_MODE_TEXT.value();
        break;
      case SET_UP_IDLE_MODE_TEXT:
        sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
        break;
      case PROVIDE_LOCAL_INFORMATION:
        ResponseData resp;
        switch (cmdParams.cmdDet.commandQualifier) {
          case CommandParamsFactory.DTTZ_SETTING:
            resp = new DTTZResponseData(null);
            sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
            break;
          case CommandParamsFactory.LANGUAGE_SETTING:
            resp = new LanguageResponseData(Locale.getDefault().getLanguage());
            sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, resp);
            break;
          default:
            sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
        }
        // No need to start STK app here.
        return;
      case LAUNCH_BROWSER:
        if ((((LaunchBrowserParams) cmdParams).confirmMsg.text != null)
            && (((LaunchBrowserParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
          message = mContext.getText(com.android.internal.R.string.launchBrowserDefault);
          ((LaunchBrowserParams) cmdParams).confirmMsg.text = message.toString();
        }
        break;
      case SELECT_ITEM:
      case GET_INPUT:
      case GET_INKEY:
        break;
      case SEND_DTMF:
      case SEND_SMS:
      case SEND_SS:
      case SEND_USSD:
        if ((((DisplayTextParams) cmdParams).textMsg.text != null)
            && (((DisplayTextParams) cmdParams).textMsg.text.equals(STK_DEFAULT))) {
          message = mContext.getText(com.android.internal.R.string.sending);
          ((DisplayTextParams) cmdParams).textMsg.text = message.toString();
        }
        break;
      case PLAY_TONE:
        break;
      case SET_UP_CALL:
        if ((((CallSetupParams) cmdParams).confirmMsg.text != null)
            && (((CallSetupParams) cmdParams).confirmMsg.text.equals(STK_DEFAULT))) {
          message = mContext.getText(com.android.internal.R.string.SetupCallDefault);
          ((CallSetupParams) cmdParams).confirmMsg.text = message.toString();
        }
        break;
      case OPEN_CHANNEL:
      case CLOSE_CHANNEL:
      case RECEIVE_DATA:
      case SEND_DATA:
        BIPClientParams cmd = (BIPClientParams) cmdParams;
        /*
         * If the text mesg is null, need to send the response
         * back to the card in the following scenarios
         * - It has alpha ID tag with no Text Msg (or)
         * - If alphaUsrCnf is not set. In the above cases
         *   there should be no UI indication given to the user.
         */
        boolean alphaUsrCnf =
            SystemProperties.getBoolean(TelephonyProperties.PROPERTY_ALPHA_USRCNF, false);
        CatLog.d(this, "alphaUsrCnf: " + alphaUsrCnf + ", bHasAlphaId: " + cmd.bHasAlphaId);

        if ((cmd.textMsg.text == null) && (cmd.bHasAlphaId || !alphaUsrCnf)) {
          CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id");
          // If alpha length is zero, we just respond with OK.
          if (isProactiveCmd) {
            sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
          } else if (cmdParams.getCommandType() == CommandType.OPEN_CHANNEL) {
            mCmdIf.handleCallSetupRequestFromSim(true, null);
          }
          return;
        }
        // Respond with permanent failure to avoid retry if STK app is not present.
        if (!mStkAppInstalled) {
          CatLog.d(this, "No STK application found.");
          if (isProactiveCmd) {
            sendTerminalResponse(
                cmdParams.cmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null);
            return;
          }
        }
        /*
         * CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by
         * either PROACTIVE_COMMAND or EVENT_NOTIFY.
         * If PROACTIVE_COMMAND is used for those commands, send terminal
         * response here.
         */
        if (isProactiveCmd
            && ((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL)
                || (cmdParams.getCommandType() == CommandType.RECEIVE_DATA)
                || (cmdParams.getCommandType() == CommandType.SEND_DATA))) {
          sendTerminalResponse(cmdParams.cmdDet, ResultCode.OK, false, 0, null);
        }
        break;
      default:
        CatLog.d(this, "Unsupported command");
        return;
    }
    mCurrntCmd = cmdMsg;
    Intent intent = new Intent(AppInterface.CAT_CMD_ACTION);
    intent.putExtra("STK CMD", cmdMsg);
    mContext.sendBroadcast(intent);
  }
  @Override
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    PhoneApp app = PhoneApp.getInstance();
    addPreferencesFromResource(R.xml.msim_network_settings);

    mSubscription = getIntent().getIntExtra(SUBSCRIPTION_KEY, app.getDefaultSubscription());
    log("Settings onCreate subscription =" + mSubscription);
    mPhone = app.getPhone(mSubscription);
    mHandler = new MyHandler();

    // get UI object references
    PreferenceScreen prefSet = getPreferenceScreen();

    mButtonPreferredNetworkMode =
        (ListPreference) prefSet.findPreference(BUTTON_PREFERED_NETWORK_MODE);

    boolean isLteOnCdma = mPhone.getLteOnCdmaMode() == Phone.LTE_ON_CDMA_TRUE;
    if (getResources().getBoolean(R.bool.world_phone) == true) {

      if (SystemProperties.getBoolean("ro.monkey", false)) {
        prefSet.removePreference(mButtonPreferredNetworkMode);
      } else {
        // set the listener for the mButtonPreferredNetworkMode list
        // preference so we can issue change Preferred Network Mode.
        mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this);

        // Get the networkMode from Settings.System and displays it
        int settingsNetworkMode =
            android.provider.Settings.Secure.getInt(
                mPhone.getContext().getContentResolver(),
                android.provider.Settings.Secure.PREFERRED_NETWORK_MODE,
                preferredNetworkMode);
        mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
        mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
        mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, mSubscription);
      }
    } else {
      if (!isLteOnCdma) {
        prefSet.removePreference(mButtonPreferredNetworkMode);
      }
      int phoneType = mPhone.getPhoneType();
      if (phoneType == Phone.PHONE_TYPE_CDMA) {
        mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
        if (isLteOnCdma) {
          mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this);
          mButtonPreferredNetworkMode.setEntries(R.array.preferred_network_mode_choices_lte);
          mButtonPreferredNetworkMode.setEntryValues(R.array.preferred_network_mode_values_lte);
          int settingsNetworkMode =
              android.provider.Settings.Secure.getInt(
                  mPhone.getContext().getContentResolver(),
                  android.provider.Settings.Secure.PREFERRED_NETWORK_MODE,
                  preferredNetworkMode);
          mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
        }

      } else if (phoneType == Phone.PHONE_TYPE_GSM) {
        mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, mSubscription);
      } else {
        throw new IllegalStateException("Unexpected phone type: " + phoneType);
      }
    }
  }
  void refreshUi(boolean dataChanged) {
    if (dataChanged) {
      ServiceListAdapter adapter = (ServiceListAdapter) (mListView.getAdapter());
      adapter.refreshItems();
      adapter.notifyDataSetChanged();
    }

    if (mDataAvail != null) {
      mDataAvail.run();
      mDataAvail = null;
    }

    // This is the amount of available memory until we start killing
    // background services.
    mMemInfoReader.readMemInfo();
    long availMem =
        mMemInfoReader.getFreeSize() + mMemInfoReader.getCachedSize() - SECONDARY_SERVER_MEM;
    if (availMem < 0) {
      availMem = 0;
    }

    /// M: get total size @{
    long totalSize = mMemInfoReader.getTotalSize();
    /// @}

    synchronized (mState.mLock) {

      /// M: get zram extra available memory @{
      long extraAvailableSize = 0;
      if (SystemProperties.getBoolean("mediatek.virtual_zram_extra", false)) {
        extraAvailableSize += Process.getZramExtraAvailableSize();
      } else {
        final long anonReserve = 15 * 1024 * 1024; // 15MB
        long anonToCompress =
            Process.getLruAnonMemory() - anonReserve - mState.mBackgroundProcessMemory;
        if (anonToCompress > 0) {
          extraAvailableSize =
              (long) (anonToCompress * (1.0f - 1.0f / Process.getZramCompressRatio()));
        }
      }
      Log.i("RunningProcessView", "extraAvailableSize = " + extraAvailableSize);
      availMem += extraAvailableSize;
      /// @}
      if (mLastNumBackgroundProcesses != mState.mNumBackgroundProcesses
          || mLastBackgroundProcessMemory != mState.mBackgroundProcessMemory
          || mLastAvailMemory != availMem) {
        mLastNumBackgroundProcesses = mState.mNumBackgroundProcesses;
        mLastBackgroundProcessMemory = mState.mBackgroundProcessMemory;
        mLastAvailMemory = availMem;
        long freeMem = mLastAvailMemory + mLastBackgroundProcessMemory;

        BidiFormatter bidiFormatter = BidiFormatter.getInstance();
        String sizeStr =
            bidiFormatter.unicodeWrap(Formatter.formatShortFileSize(getContext(), freeMem));

        mBackgroundProcessText.setText(
            getResources().getString(R.string.service_background_processes, sizeStr));

        sizeStr =
            bidiFormatter.unicodeWrap(
                Formatter.formatShortFileSize(
                    getContext(), mMemInfoReader.getTotalSize() - freeMem));

        mForegroundProcessText.setText(
            getResources().getString(R.string.service_foreground_processes, sizeStr));
      }
      if (mLastNumForegroundProcesses != mState.mNumForegroundProcesses
          || mLastForegroundProcessMemory != mState.mForegroundProcessMemory
          || mLastNumServiceProcesses != mState.mNumServiceProcesses
          || mLastServiceProcessMemory != mState.mServiceProcessMemory) {
        mLastNumForegroundProcesses = mState.mNumForegroundProcesses;
        mLastForegroundProcessMemory = mState.mForegroundProcessMemory;
        mLastNumServiceProcesses = mState.mNumServiceProcesses;
        mLastServiceProcessMemory = mState.mServiceProcessMemory;
        /*
        String sizeStr = Formatter.formatShortFileSize(getContext(),
                mLastForegroundProcessMemory + mLastServiceProcessMemory);
        mForegroundProcessText.setText(getResources().getString(
                R.string.service_foreground_processes, sizeStr));
        */
      }
      /// M: get swap usage @{
      float totalMem = totalSize;
      float totalShownMem = availMem + mLastBackgroundProcessMemory + mLastServiceProcessMemory;
      Log.i(
          "RunningProcessView",
          "totalShownMem = "
              + mMemInfoReader.getFreeSize()
              + " + "
              + mMemInfoReader.getCachedSize()
              + " - "
              + SECONDARY_SERVER_MEM
              + " + "
              + mLastBackgroundProcessMemory
              + " + "
              + mLastServiceProcessMemory);
      /// @}
      mColorBar.setRatios(
          (totalMem - totalShownMem) / totalMem,
          mLastServiceProcessMemory / totalMem,
          mLastBackgroundProcessMemory / totalMem);
    }
  }
Example #19
0
 /**
  * Returns whether the Encrypted File System feature is enabled on the device or not.
  *
  * @return <code>true</code> if Encrypted File System feature is enabled, <code>false</code> if
  *     disabled.
  * @hide
  */
 public static boolean isEncryptedFilesystemEnabled() {
   return SystemProperties.getBoolean(SYSTEM_PROPERTY_EFS_ENABLED, false);
 }
/** {@hide} */
public final class CdmaDataProfileTracker extends Handler {
  protected final String LOG_TAG = "CDMA";

  static final Uri PREFER_DEFAULT_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

  private CDMAPhone mPhone;
  private CdmaSubscriptionSourceManager mCdmaSsm;

  /** mDataProfilesList holds all the Data profiles for cdma */
  private ArrayList<DataProfile> mDataProfilesList = new ArrayList<DataProfile>();

  private static final String[] mSupportedApnTypes = {
    Phone.APN_TYPE_DEFAULT,
    Phone.APN_TYPE_MMS,
    Phone.APN_TYPE_SUPL,
    Phone.APN_TYPE_DUN,
    Phone.APN_TYPE_HIPRI,
    Phone.APN_TYPE_FOTA,
    Phone.APN_TYPE_IMS,
    Phone.APN_TYPE_CBS
  };

  private static final String[] mDefaultApnTypes = {
    Phone.APN_TYPE_DEFAULT,
    Phone.APN_TYPE_MMS,
    Phone.APN_TYPE_SUPL,
    Phone.APN_TYPE_HIPRI,
    Phone.APN_TYPE_FOTA,
    Phone.APN_TYPE_IMS,
    Phone.APN_TYPE_CBS
  };

  // if we have no active DataProfile this is null
  protected DataProfile mActiveDp;

  /*
   * Context for read profiles for OMH.
   */
  private int mOmhReadProfileContext = 0;

  /*
   * Count to track if all read profiles for OMH are completed or not.
   */
  private int mOmhReadProfileCount = 0;

  private boolean mIsOmhEnabled =
      SystemProperties.getBoolean(TelephonyProperties.PROPERTY_OMH_ENABLED, false);

  // Enumerated list of DataProfile from the modem.
  ArrayList<DataProfile> mOmhDataProfilesList = new ArrayList<DataProfile>();

  // Temp. DataProfile list from the modem.
  ArrayList<DataProfile> mTempOmhDataProfilesList = new ArrayList<DataProfile>();

  // Map of the service type to its priority
  HashMap<String, Integer> mOmhServicePriorityMap;

  /* Registrant list for objects interested in modem profile related events */
  private RegistrantList mModemDataProfileRegistrants = new RegistrantList();

  private static final int EVENT_READ_MODEM_PROFILES = 0;
  private static final int EVENT_GET_DATA_CALL_PROFILE_DONE = 1;
  private static final int EVENT_LOAD_PROFILES = 2;

  /* Constructor */

  CdmaDataProfileTracker(CDMAPhone phone) {
    mPhone = phone;
    mCdmaSsm =
        CdmaSubscriptionSourceManager.getInstance(
            phone.getContext(), phone.mCM, this, EVENT_LOAD_PROFILES, null);

    mOmhServicePriorityMap = new HashMap<String, Integer>();

    sendMessage(obtainMessage(EVENT_LOAD_PROFILES));

    log("SUPPORT_OMH: " + mIsOmhEnabled);
  }

  /** Load the CDMA profiles */
  void loadProfiles() {
    log("loadProfiles...");
    mDataProfilesList.clear();

    readNaiListFromDatabase();

    log("Got " + mDataProfilesList.size() + " profiles from database");

    if (mDataProfilesList.size() == 0) {
      // Create default cdma profiles since nothing was found in database
      createDefaultDataProfiles();
    }

    // Set the active profile as the default one
    setActiveDpToDefault();

    // Last thing - trigger reading omh profiles
    readDataProfilesFromModem();
  }

  /**
   * - Create the default profiles. - One for DUN and another for all the default profiles supported
   */
  private void createDefaultDataProfiles() {
    log("Creating default profiles...");
    String ipProto = SystemProperties.get(TelephonyProperties.PROPERTY_CDMA_IPPROTOCOL, "IP");
    String roamingIpProto =
        SystemProperties.get(TelephonyProperties.PROPERTY_CDMA_ROAMING_IPPROTOCOL, "IP");
    CdmaDataConnectionTracker cdmaDct = (CdmaDataConnectionTracker) (mPhone.mDataConnectionTracker);

    DataProfileCdma dp;
    dp =
        new DataProfileCdma(
            cdmaDct.apnTypeToId(Phone.APN_TYPE_DEFAULT),
            null,
            null,
            null,
            null,
            RILConstants.SETUP_DATA_AUTH_PAP_CHAP,
            mDefaultApnTypes,
            ipProto,
            roamingIpProto,
            mPhone.getServiceState().getRadioTechnology());
    dp.setProfileId(RILConstants.DATA_PROFILE_DEFAULT);
    mDataProfilesList.add((DataProfile) dp);

    String[] types = {Phone.APN_TYPE_DUN};

    dp =
        new DataProfileCdma(
            cdmaDct.apnTypeToId(Phone.APN_TYPE_DUN),
            null,
            null,
            null,
            null,
            RILConstants.SETUP_DATA_AUTH_PAP_CHAP,
            types,
            ipProto,
            roamingIpProto,
            mPhone.getServiceState().getRadioTechnology());
    dp.setProfileId(RILConstants.DATA_PROFILE_TETHERED);
    mDataProfilesList.add((DataProfile) dp);
  }

  private void setActiveDpToDefault() {
    mActiveDp = getDataProfile(Phone.APN_TYPE_DEFAULT);
  }

  private String getOperatorNumeric() {
    String result = null;
    CdmaDataConnectionTracker cdmaDct = (CdmaDataConnectionTracker) (mPhone.mDataConnectionTracker);
    if (mCdmaSsm.getCdmaSubscriptionSource()
        == CdmaSubscriptionSourceManager.SUBSCRIPTION_FROM_NV) {
      result = SystemProperties.get(CDMAPhone.PROPERTY_CDMA_HOME_OPERATOR_NUMERIC);
      log("operatorNumeric for NV " + result);
    } else if (cdmaDct.getIccRecords() != null) {
      result = cdmaDct.getIccRecords().getOperatorNumeric();
      log("operatorNumeric for icc " + result);
    } else {
      log("IccRecords == null -> operatorNumeric = null");
    }
    return result;
  }

  /** Based on the operator, create a list of cdma data profiles. */
  private void readNaiListFromDatabase() {
    String operator = getOperatorNumeric();
    if (operator == null || operator.length() < 2) {
      loge("operatorNumeric invalid. Won't read database");
      return;
    }

    log("Loading data profiles for operator = " + operator);
    String selection = "numeric = '" + operator + "'";
    // query only enabled nai.
    // carrier_enabled : 1 means enabled nai, 0 disabled nai.
    selection += " and carrier_enabled = 1";
    log("readNaiListFromDatabase: selection=" + selection);

    Cursor cursor =
        mPhone
            .getContext()
            .getContentResolver()
            .query(Telephony.Carriers.CONTENT_URI, null, selection, null, null);

    if (cursor != null) {
      if (cursor.getCount() > 0) {
        populateDataProfilesList(cursor);
      }
      cursor.close();
    }
  }

  private void populateDataProfilesList(Cursor cursor) {
    if (cursor.moveToFirst()) {
      do {
        String[] types =
            parseTypes(cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE)));
        DataProfileCdma nai =
            new DataProfileCdma(
                cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)),
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)),
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)),
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
                cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
                types,
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROTOCOL)),
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.ROAMING_PROTOCOL)),
                cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.BEARER)));
        mDataProfilesList.add(nai);

      } while (cursor.moveToNext());
    }
  }

  /**
   * @param types comma delimited list of data service types
   * @return array of data service types
   */
  private String[] parseTypes(String types) {
    String[] result;
    // If unset, set to DEFAULT.
    if (types == null || types.equals("")) {
      result = new String[1];
      result[0] = Phone.APN_TYPE_ALL;
    } else {
      result = types.split(",");
    }
    return result;
  }

  public void dispose() {}

  protected void finalize() {
    Log.d(LOG_TAG, "CdmaDataProfileTracker finalized");
  }

  void registerForModemProfileReady(Handler h, int what, Object obj) {
    Registrant r = new Registrant(h, what, obj);
    mModemDataProfileRegistrants.add(r);
  }

  void unregisterForModemProfileReady(Handler h) {
    mModemDataProfileRegistrants.remove(h);
  }

  public void handleMessage(Message msg) {

    if (!mPhone.mIsTheCurrentActivePhone) {
      Log.d(LOG_TAG, "Ignore CDMA msgs since CDMA phone is inactive");
      return;
    }

    switch (msg.what) {
      case EVENT_LOAD_PROFILES:
        loadProfiles();
        break;
      case EVENT_READ_MODEM_PROFILES:
        onReadDataProfilesFromModem();
        break;

      case EVENT_GET_DATA_CALL_PROFILE_DONE:
        onGetDataCallProfileDone((AsyncResult) msg.obj, (int) msg.arg1);
        break;

      default:
        // handle the message in the super class DataConnectionTracker
        super.handleMessage(msg);
        break;
    }
  }

  /*
   * Trigger modem read for data profiles
   */
  private void readDataProfilesFromModem() {
    if (mIsOmhEnabled) {
      sendMessage(obtainMessage(EVENT_READ_MODEM_PROFILES));
    } else {
      log("OMH is disabled, ignoring request!");
    }
  }

  /*
   * Reads all the data profiles from the modem
   */
  private void onReadDataProfilesFromModem() {
    log("OMH: onReadDataProfilesFromModem()");
    mOmhReadProfileContext++;

    mOmhReadProfileCount = 0; // Reset the count and list(s)
    /* Clear out the modem profiles lists (main and temp) which were read/saved */
    mOmhDataProfilesList.clear();
    mTempOmhDataProfilesList.clear();
    mOmhServicePriorityMap.clear();

    // For all the service types known in modem, read the data profies
    for (DataProfileTypeModem p : DataProfileTypeModem.values()) {
      log("OMH: Reading profiles for:" + p.getid());
      mOmhReadProfileCount++;
      mPhone.mCM.getDataCallProfile(
          p.getid(),
          obtainMessage(
              EVENT_GET_DATA_CALL_PROFILE_DONE, // what
              mOmhReadProfileContext, // arg1
              0, // arg2  -- ignore
              p)); // userObj
    }
  }

  /*
   * Process the response for the RIL request GET_DATA_CALL_PROFILE.
   * Save the profile details received.
   */
  private void onGetDataCallProfileDone(AsyncResult ar, int context) {
    if (ar.exception != null) {
      log("OMH: Exception in onGetDataCallProfileDone:" + ar.exception);
      return;
    }

    if (context != mOmhReadProfileContext) {
      // we have other onReadOmhDataprofiles() on the way.
      return;
    }

    // DataProfile list from the modem for a given SERVICE_TYPE. These may
    // be from RUIM in case of OMH
    ArrayList<DataProfile> dataProfileListModem = new ArrayList<DataProfile>();
    dataProfileListModem = (ArrayList<DataProfile>) ar.result;

    DataProfileTypeModem modemProfile = (DataProfileTypeModem) ar.userObj;

    mOmhReadProfileCount--;

    if (dataProfileListModem != null && dataProfileListModem.size() > 0) {
      String serviceType;

      /* For the modem service type, get the android DataServiceType */
      serviceType = modemProfile.getDataServiceType();

      log(
          "OMH: # profiles returned from modem:"
              + dataProfileListModem.size()
              + " for "
              + serviceType);

      mOmhServicePriorityMap.put(
          serviceType, omhListGetArbitratedPriority(dataProfileListModem, serviceType));

      for (DataProfile dp : dataProfileListModem) {

        /* Store the modem profile type in the data profile */
        ((DataProfileOmh) dp).setDataProfileTypeModem(modemProfile);

        /* Look through mTempOmhDataProfilesList for existing profile id's
         * before adding it. This implies that the (similar) profile with same
         * priority already exists.
         */
        DataProfileOmh omhDuplicatedp = getDuplicateProfile(dp);
        if (null == omhDuplicatedp) {
          mTempOmhDataProfilesList.add(dp);
          ((DataProfileOmh) dp)
              .addServiceType(DataProfileTypeModem.getDataProfileTypeModem(serviceType));
        } else {
          /*  To share the already established data connection
           * (say between SUPL and DUN) in cases such as below:
           *  Ex:- SUPL+DUN [profile id 201, priority 1]
           *  'dp' instance is found at this point. Add the non-provisioned
           *   service type to this 'dp' instance
           */
          log("OMH: Duplicate Profile " + omhDuplicatedp);
          ((DataProfileOmh) omhDuplicatedp)
              .addServiceType(DataProfileTypeModem.getDataProfileTypeModem(serviceType));
        }
      }
    }

    // (Re)Load APN List
    if (mOmhReadProfileCount == 0) {
      log("OMH: Modem omh profile read complete.");
      addServiceTypeToUnSpecified();
      mDataProfilesList.addAll(mTempOmhDataProfilesList);
      mModemDataProfileRegistrants.notifyRegistrants();
    }

    return;
  }

  /*
   * returns the object 'OMH dataProfile' if a match with the same profile id
   * exists in the enumerated list of OMH profile list
   */
  private DataProfileOmh getDuplicateProfile(DataProfile dp) {
    for (DataProfile dataProfile : mTempOmhDataProfilesList) {
      if (((DataProfileOmh) dp).getProfileId() == ((DataProfileOmh) dataProfile).getProfileId()) {
        return (DataProfileOmh) dataProfile;
      }
    }
    return null;
  }

  public DataProfile getDataProfile(String serviceType) {
    DataProfile profile = null;

    // first try to get preferred APN

    String operator = getOperatorNumeric();
    String selection = "numeric = '" + operator + "'";
    // query only enabled nai.
    // carrier_enabled : 1 means enabled nai, 0 disabled nai.
    selection += " and carrier_enabled = 1";
    Cursor cursor =
        mPhone
            .getContext()
            .getContentResolver()
            .query(PREFER_DEFAULT_APN_URI, null, selection, null, null);

    log(
        "getDataProfile operator:"
            + operator
            + " select:"
            + selection
            + " count:"
            + cursor.getCount());
    if (cursor != null && cursor.getCount() > 0) {
      if (cursor.moveToFirst()) {
        do {
          String[] types =
              parseTypes(cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.TYPE)));
          DataProfile nai =
              new DataProfileCdma(
                  cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers._ID)),
                  cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.NUMERIC)),
                  cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.APN)),
                  cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.USER)),
                  cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PASSWORD)),
                  cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.AUTH_TYPE)),
                  types,
                  cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Carriers.PROTOCOL)),
                  cursor.getString(
                      cursor.getColumnIndexOrThrow(Telephony.Carriers.ROAMING_PROTOCOL)),
                  cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Carriers.BEARER)));
          if (nai.canHandleType(serviceType)) {
            cursor.close();
            return nai;
          }
        } while (cursor.moveToNext());
      }
    }

    if (cursor != null) cursor.close();

    // Go through all the profiles to find one
    for (DataProfile dp : mDataProfilesList) {
      if (dp.canHandleType(serviceType)) {
        profile = dp;
        if (mIsOmhEnabled
            && dp.getDataProfileType() != DataProfile.DataProfileType.PROFILE_TYPE_OMH) {
          // OMH enabled - Keep looking for OMH profile
          continue;
        }
        break;
      }
    }
    return profile;
  }

  /* For all the OMH service types not present in the card, add them to the
   * UNSPECIFIED/DEFAULT data profile.
   */
  private void addServiceTypeToUnSpecified() {
    for (String apntype : mSupportedApnTypes) {
      if (!mOmhServicePriorityMap.containsKey(apntype)) {

        // ServiceType :apntype is not provisioned in the card,
        // Look through the profiles read from the card to locate
        // the UNSPECIFIED profile and add the service type to it.
        for (DataProfile dp : mTempOmhDataProfilesList) {
          if (((DataProfileOmh) dp).getDataProfileTypeModem()
              == DataProfileTypeModem.PROFILE_TYPE_UNSPECIFIED) {
            ((DataProfileOmh) dp)
                .addServiceType(DataProfileTypeModem.getDataProfileTypeModem(apntype));
            log(
                "OMH: Service Type added to UNSPECIFIED is : "
                    + DataProfileTypeModem.getDataProfileTypeModem(apntype));
            break;
          }
        }
      }
    }
  }

  /*
   * Retrieves the highest priority for all APP types except SUPL. Note that
   * for SUPL, retrieve the least priority among its profiles.
   */
  private int omhListGetArbitratedPriority(
      ArrayList<DataProfile> dataProfileListModem, String serviceType) {
    DataProfile profile = null;

    for (DataProfile dp : dataProfileListModem) {
      if (!((DataProfileOmh) dp).isValidPriority()) {
        log("[OMH] Invalid priority... skipping");
        continue;
      }

      if (profile == null) {
        profile = dp; // first hit
      } else {
        if (serviceType == Phone.APN_TYPE_SUPL) {
          // Choose the profile with lower priority
          profile =
              ((DataProfileOmh) dp).isPriorityLower(((DataProfileOmh) profile).getPriority())
                  ? dp
                  : profile;
        } else {
          // Choose the profile with higher priority
          profile =
              ((DataProfileOmh) dp).isPriorityHigher(((DataProfileOmh) profile).getPriority())
                  ? dp
                  : profile;
        }
      }
    }
    return ((DataProfileOmh) profile).getPriority();
  }

  public void clearActiveDataProfile() {
    mActiveDp = null;
  }

  public boolean isApnTypeActive(String type) {
    return mActiveDp != null && mActiveDp.canHandleType(type);
  }

  public boolean isOmhEnabled() {
    return mIsOmhEnabled;
  }

  protected boolean isApnTypeAvailable(String type) {
    for (String s : mSupportedApnTypes) {
      if (TextUtils.equals(type, s)) {
        return true;
      }
    }
    return false;
  }

  protected String[] getActiveApnTypes() {
    String[] result;
    if (mActiveDp != null) {
      result = mActiveDp.getServiceTypes();
    } else {
      result = new String[1];
      result[0] = Phone.APN_TYPE_DEFAULT;
    }
    return result;
  }

  protected void log(String s) {
    Log.d(LOG_TAG, "[CdmaDataProfileTracker] " + s);
  }

  protected void loge(String s) {
    Log.e(LOG_TAG, "[CdmaDataProfileTracker] " + s);
  }
}
 private void updateHardwareUiOptions() {
   mForceHardwareUi.setChecked(SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
 }
 private boolean shouldEnableKeyguardScreenRotation() {
   Resources res = mContext.getResources();
   return SystemProperties.getBoolean("lockscreen.rot_override", false)
       || res.getBoolean(R.bool.config_enableLockScreenRotation);
 }
 private static void preloadOpenGL() {
   if (!SystemProperties.getBoolean(PROPERTY_DISABLE_OPENGL_PRELOADING, false)) {
     EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
   }
 }
 private void updateShowHwOverdrawOptions() {
   updateCheckBox(
       mShowHwOverdraw,
       SystemProperties.getBoolean(HardwareRenderer.DEBUG_SHOW_OVERDRAW_PROPERTY, false));
 }
 private void updateShowHwLayersUpdatesOptions() {
   updateCheckBox(
       mShowHwLayersUpdates,
       SystemProperties.getBoolean(HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
 }
  /** Show the keyguard. Will handle creating and attaching to the view manager lazily. */
  public synchronized void show() {
    if (DEBUG) Log.d(TAG, "show(); mKeyguardView==" + mKeyguardView);

    Resources res = mContext.getResources();
    boolean enableScreenRotation =
        SystemProperties.getBoolean("lockscreen.rot_override", false)
            || res.getBoolean(R.bool.config_enableLockScreenRotation);
    enableScreenRotation =
        Settings.System.getInt(
                mContext.getContentResolver(),
                Settings.System.LOCKSCREEN_LANDSCAPE,
                enableScreenRotation ? 1 : 0)
            == 1;
    if (mKeyguardHost == null) {
      if (DEBUG) Log.d(TAG, "keyguard host is null, creating it...");

      mKeyguardHost = new KeyguardViewHost(mContext, mCallback);

      final int stretch = ViewGroup.LayoutParams.MATCH_PARENT;
      int flags =
          WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN
              | WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER
              | WindowManager.LayoutParams.FLAG_KEEP_SURFACE_WHILE_ANIMATING
          /*| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
          | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR*/ ;
      if (!mNeedsInput) {
        flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
      }
      if (ActivityManager.isHighEndGfx(
          ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
              .getDefaultDisplay())) {
        flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
      }
      WindowManager.LayoutParams lp =
          new WindowManager.LayoutParams(
              stretch,
              stretch,
              WindowManager.LayoutParams.TYPE_KEYGUARD,
              flags,
              PixelFormat.TRANSLUCENT);
      lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
      lp.windowAnimations = com.android.internal.R.style.Animation_LockScreen;
      if (ActivityManager.isHighEndGfx(
          ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
              .getDefaultDisplay())) {
        lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
        lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
      }
      lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SET_NEEDS_MENU_KEY;
      lp.setTitle("Keyguard");
      mWindowLayoutParams = lp;

      mViewManager.addView(mKeyguardHost, lp);
    }

    if (enableScreenRotation
        && Settings.System.getInt(
                mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1)
            == 1) {
      if (DEBUG) Log.d(TAG, "Rotation sensor for lock screen On!");
      mWindowLayoutParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
    } else {
      if (DEBUG) Log.d(TAG, "Rotation sensor for lock screen Off!");
      mWindowLayoutParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
    }

    mViewManager.updateViewLayout(mKeyguardHost, mWindowLayoutParams);

    if (mKeyguardView == null) {
      if (DEBUG) Log.d(TAG, "keyguard view is null, creating it...");
      mKeyguardView = mKeyguardViewProperties.createKeyguardView(mContext, mUpdateMonitor, this);
      mKeyguardView.setId(R.id.lock_screen);
      mKeyguardView.setCallback(mCallback);

      final ViewGroup.LayoutParams lp =
          new FrameLayout.LayoutParams(
              ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

      mKeyguardHost.addView(mKeyguardView, lp);

      if (mScreenOn) {
        mKeyguardView.show();
      }
    }

    // Disable aspects of the system/status/navigation bars that are not appropriate or
    // useful for the lockscreen but can be re-shown by dialogs or SHOW_WHEN_LOCKED activities.
    // Other disabled bits are handled by the KeyguardViewMediator talking directly to the
    // status bar service.
    int visFlags = (View.STATUS_BAR_DISABLE_BACK | View.STATUS_BAR_DISABLE_HOME);
    mKeyguardHost.setSystemUiVisibility(visFlags);

    mViewManager.updateViewLayout(mKeyguardHost, mWindowLayoutParams);
    mKeyguardHost.setVisibility(View.VISIBLE);
    mKeyguardView.requestFocus();
  }
 /*
  * M: Initialize layout debugging.
  */
 private void initFrameLayout() {
   DEBUG_LAYOUT = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
 }
public class SamsungRIL extends RIL implements CommandsInterface {

  private boolean mSignalbarCount =
      SystemProperties.getInt("ro.telephony.sends_barcount", 0) == 1 ? true : false;

  private boolean mIsSamsungCdma = SystemProperties.getBoolean("ro.ril.samsung_cdma", false);

  public SamsungRIL(Context context, int networkMode, int cdmaSubscription) {
    super(context, networkMode, cdmaSubscription);
  }

  // SAMSUNG SGS STATES
  static final int RIL_UNSOL_STK_SEND_SMS_RESULT = 11002;
  static final int RIL_UNSOL_O2_HOME_ZONE_INFO = 11007;
  static final int RIL_UNSOL_DEVICE_READY_NOTI = 11008;
  static final int RIL_UNSOL_SAMSUNG_UNKNOWN_MAGIC_REQUEST_3 = 11010;
  static final int RIL_UNSOL_SAMSUNG_UNKNOWN_MAGIC_REQUEST_2 = 11011;
  static final int RIL_UNSOL_HSDPA_STATE_CHANGED = 11016;
  static final int RIL_UNSOL_SAMSUNG_UNKNOWN_MAGIC_REQUEST = 11012;
  static final int RIL_REQUEST_DIAL_EMERGENCY = 10016;

  @Override
  public void setRadioPower(boolean on, Message result) {
    RILRequest rr = RILRequest.obtain(RIL_REQUEST_RADIO_POWER, result);

    // samsung crap for airplane mode
    if (on) {
      rr.mp.writeInt(1);
      rr.mp.writeInt(1);
    } else {
      rr.mp.writeInt(2);
      rr.mp.writeInt(0);
      rr.mp.writeInt(0);
    }
    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));
    send(rr);
  }

  @Override
  protected void processSolicited(Parcel p) {
    int serial, error;
    boolean found = false;

    serial = p.readInt();
    error = p.readInt();

    Log.d(LOG_TAG, "Serial: " + serial);
    Log.d(LOG_TAG, "Error: " + error);

    RILRequest rr;

    rr = findAndRemoveRequestFromList(serial);

    if (rr == null) {
      Log.w(LOG_TAG, "Unexpected solicited response! sn: " + serial + " error: " + error);
      return;
    }

    Object ret = null;

    if (error == 0 || p.dataAvail() > 0) {
      // either command succeeds or command fails but with data payload
      try {
        switch (rr.mRequest) {
            /*
            cat libs/telephony/ril_commands.h \
            | egrep "^ *{RIL_" \
            | sed -re 's/\{([^,]+),[^,]+,([^}]+).+/case \1: ret = \2(p); break;/'
             */
          case RIL_REQUEST_GET_SIM_STATUS:
            ret = responseIccCardStatus(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PIN:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PUK:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PIN2:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PUK2:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CHANGE_SIM_PIN:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CHANGE_SIM_PIN2:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_GET_CURRENT_CALLS:
            ret = responseCallList(p);
            break;
          case RIL_REQUEST_DIAL:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_IMSI:
            ret = responseString(p);
            break;
          case RIL_REQUEST_HANGUP:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CONFERENCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_UDUB:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_LAST_CALL_FAIL_CAUSE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SIGNAL_STRENGTH:
            ret = responseSignalStrength(p);
            break;
          case RIL_REQUEST_VOICE_REGISTRATION_STATE:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_DATA_REGISTRATION_STATE:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_OPERATOR:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_RADIO_POWER:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DTMF:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SEND_SMS:
            ret = responseSMS(p);
            break;
          case RIL_REQUEST_SEND_SMS_EXPECT_MORE:
            ret = responseSMS(p);
            break;
          case RIL_REQUEST_SETUP_DATA_CALL:
            ret = responseSetupDataCall(p);
            break;
          case RIL_REQUEST_SIM_IO:
            ret = responseICC_IO(p);
            break;
          case RIL_REQUEST_SEND_USSD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CANCEL_USSD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_CLIR:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_CLIR:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS:
            ret = responseCallForward(p);
            break;
          case RIL_REQUEST_SET_CALL_FORWARD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_CALL_WAITING:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_CALL_WAITING:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SMS_ACKNOWLEDGE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_IMEI:
            ret = responseString(p);
            break;
          case RIL_REQUEST_GET_IMEISV:
            ret = responseString(p);
            break;
          case RIL_REQUEST_ANSWER:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DEACTIVATE_DATA_CALL:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_FACILITY_LOCK:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_FACILITY_LOCK:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CHANGE_BARRING_PASSWORD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS:
            ret = responseOperatorInfos(p);
            break;
          case RIL_REQUEST_DTMF_START:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DTMF_STOP:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_BASEBAND_VERSION:
            ret = responseString(p);
            break;
          case RIL_REQUEST_SEPARATE_CONNECTION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_MUTE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_MUTE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_QUERY_CLIP:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_DATA_CALL_LIST:
            ret = responseDataCallList(p);
            break;
          case RIL_REQUEST_RESET_RADIO:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_OEM_HOOK_RAW:
            ret = responseRaw(p);
            break;
          case RIL_REQUEST_OEM_HOOK_STRINGS:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_SCREEN_STATE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_WRITE_SMS_TO_SIM:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_DELETE_SMS_ON_SIM:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_BAND_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_STK_GET_PROFILE:
            ret = responseString(p);
            break;
          case RIL_REQUEST_STK_SET_PROFILE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND:
            ret = responseString(p);
            break;
          case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_EXPLICIT_CALL_TRANSFER:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
            ret = responseNetworkType(p);
            break;
          case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
            ret = responseCellList(p);
            break;
          case RIL_REQUEST_SET_LOCATION_UPDATES:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_TTY_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_TTY_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CDMA_FLASH:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_BURST_DTMF:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SEND_SMS:
            ret = responseSMS(p);
            break;
          case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GSM_GET_BROADCAST_CONFIG:
            ret = responseGmsBroadcastConfig(p);
            break;
          case RIL_REQUEST_GSM_SET_BROADCAST_CONFIG:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GSM_BROADCAST_ACTIVATION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_GET_BROADCAST_CONFIG:
            ret = responseCdmaBroadcastConfig(p);
            break;
          case RIL_REQUEST_CDMA_SET_BROADCAST_CONFIG:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_BROADCAST_ACTIVATION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SUBSCRIPTION:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DEVICE_IDENTITY:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_GET_SMSC_ADDRESS:
            ret = responseString(p);
            break;
          case RIL_REQUEST_SET_SMSC_ADDRESS:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING:
            ret = responseVoid(p);
            break;
          default:
            throw new RuntimeException("Unrecognized solicited response: " + rr.mRequest);
            // break;
        }
      } catch (Throwable tr) {
        // Exceptions here usually mean invalid RIL responses

        Log.w(
            LOG_TAG,
            rr.serialString()
                + "< "
                + requestToString(rr.mRequest)
                + " exception, possible invalid RIL response",
            tr);

        if (rr.mResult != null) {
          AsyncResult.forMessage(rr.mResult, null, tr);
          rr.mResult.sendToTarget();
        }
        rr.release();
        return;
      }
    }

    if (error != 0) {
      // ugly fix for Samsung messing up SMS_SEND request fail in binary RIL
      if (!(error == -1 && rr.mRequest == RIL_REQUEST_SEND_SMS)) {
        rr.onError(error, ret);
        rr.release();
        return;
      } else {
        try {
          ret = responseSMS(p);
        } catch (Throwable tr) {
          Log.w(
              LOG_TAG,
              rr.serialString()
                  + "< "
                  + requestToString(rr.mRequest)
                  + " exception, Processing Samsung SMS fix ",
              tr);
          rr.onError(error, ret);
          rr.release();
          return;
        }
      }
    }

    if (RILJ_LOGD)
      riljLog(
          rr.serialString()
              + "< "
              + requestToString(rr.mRequest)
              + " "
              + retToString(rr.mRequest, ret));

    if (rr.mResult != null) {
      AsyncResult.forMessage(rr.mResult, ret, null);
      rr.mResult.sendToTarget();
    }

    rr.release();
  }

  @Override
  public void dial(String address, int clirMode, UUSInfo uusInfo, Message result) {
    RILRequest rr;
    if (PhoneNumberUtils.isEmergencyNumber(address)) {
      Log.v(LOG_TAG, "Emergency dial: " + address);
      rr = RILRequest.obtain(RIL_REQUEST_DIAL_EMERGENCY, result);
      rr.mp.writeString(address + "/");
    } else {
      rr = RILRequest.obtain(RIL_REQUEST_DIAL, result);
      rr.mp.writeString(address);
    }

    rr.mp.writeInt(clirMode);
    rr.mp.writeInt(0); // UUS information is absent

    if (uusInfo == null) {
      rr.mp.writeInt(0); // UUS information is absent
    } else {
      rr.mp.writeInt(1); // UUS information is present
      rr.mp.writeInt(uusInfo.getType());
      rr.mp.writeInt(uusInfo.getDcs());
      rr.mp.writeByteArray(uusInfo.getUserData());
    }

    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));

    send(rr);
  }

  @Override
  protected void processUnsolicited(Parcel p) {
    int response;
    Object ret;

    response = p.readInt();

    try {
      switch (response) {
          /*
          cat libs/telephony/ril_unsol_commands.h \
          | egrep "^ *{RIL_" \
          | sed -re 's/\{([^,]+),[^,]+,([^}]+).+/case \1: \2(rr, p); break;/'
               */

        case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_RESPONSE_NEW_SMS:
          ret = responseString(p);
          break;
        case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT:
          ret = responseString(p);
          break;
        case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM:
          ret = responseInts(p);
          break;
        case RIL_UNSOL_ON_USSD:
          ret = responseStrings(p);
          break;
        case RIL_UNSOL_NITZ_TIME_RECEIVED:
          ret = responseString(p);
          break;
        case RIL_UNSOL_SIGNAL_STRENGTH:
          ret = responseSignalStrength(p);
          break;
        case RIL_UNSOL_DATA_CALL_LIST_CHANGED:
          ret = responseDataCallList(p);
          break;
        case RIL_UNSOL_SUPP_SVC_NOTIFICATION:
          ret = responseSuppServiceNotification(p);
          break;
        case RIL_UNSOL_STK_SESSION_END:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_STK_PROACTIVE_COMMAND:
          ret = responseString(p);
          break;
        case RIL_UNSOL_STK_EVENT_NOTIFY:
          ret = responseString(p);
          break;
        case RIL_UNSOL_STK_CALL_SETUP:
          ret = responseInts(p);
          break;
        case RIL_UNSOL_SIM_SMS_STORAGE_FULL:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_SIM_REFRESH:
          ret = responseInts(p);
          break;
        case RIL_UNSOL_CALL_RING:
          ret = responseCallRing(p);
          break;
        case RIL_UNSOL_RESTRICTED_STATE_CHANGED:
          ret = responseInts(p);
          break;
        case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS:
          ret = responseCdmaSms(p);
          break;
        case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS:
          ret = responseString(p);
          break;
        case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_CDMA_CALL_WAITING:
          ret = responseCdmaCallWaiting(p);
          break;
        case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS:
          ret = responseInts(p);
          break;
        case RIL_UNSOL_CDMA_INFO_REC:
          ret = responseCdmaInformationRecord(p);
          break;
        case RIL_UNSOL_OEM_HOOK_RAW:
          ret = responseRaw(p);
          break;
        case RIL_UNSOL_RINGBACK_TONE:
          ret = responseInts(p);
          break;
        case RIL_UNSOL_RESEND_INCALL_MUTE:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_HSDPA_STATE_CHANGED:
          ret = responseVoid(p);
          break;

          // fixing anoying Exceptions caused by the new Samsung states
          // FIXME figure out what the states mean an what data is in the parcel

        case RIL_UNSOL_O2_HOME_ZONE_INFO:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_STK_SEND_SMS_RESULT:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_DEVICE_READY_NOTI:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_SAMSUNG_UNKNOWN_MAGIC_REQUEST:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_SAMSUNG_UNKNOWN_MAGIC_REQUEST_2:
          ret = responseVoid(p);
          break;
        case RIL_UNSOL_SAMSUNG_UNKNOWN_MAGIC_REQUEST_3:
          ret = responseVoid(p);
          break;

        default:
          throw new RuntimeException("Unrecognized unsol response: " + response);
          // break; (implied)
      }
    } catch (Throwable tr) {
      Log.e(
          LOG_TAG,
          "Exception processing unsol response: " + response + "Exception:" + tr.toString());
      return;
    }

    switch (response) {
      case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
        /* has bonus radio state int */
        RadioState newState = getRadioStateFromInt(p.readInt());
        if (RILJ_LOGD) unsljLogMore(response, newState.toString());

        switchToRadioState(newState);
        break;
      case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED:
        if (RILJ_LOGD) unsljLog(response);

        mCallStateRegistrants.notifyRegistrants(new AsyncResult(null, null, null));
        break;
      case RIL_UNSOL_HSDPA_STATE_CHANGED:
        if (RILJ_LOGD) unsljLog(response);

        mVoiceNetworkStateRegistrants.notifyRegistrants(new AsyncResult(null, null, null));
        break;

      case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED:
        if (RILJ_LOGD) unsljLog(response);

        mVoiceNetworkStateRegistrants.notifyRegistrants(new AsyncResult(null, null, null));
        break;
      case RIL_UNSOL_RESPONSE_NEW_SMS:
        {
          if (RILJ_LOGD) unsljLog(response);

          // FIXME this should move up a layer
          String a[] = new String[2];

          a[1] = (String) ret;

          SmsMessage sms;

          sms = SmsMessage.newFromCMT(a);
          if (mGsmSmsRegistrant != null) {
            mGsmSmsRegistrant.notifyRegistrant(new AsyncResult(null, sms, null));
          }
          break;
        }
      case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mSmsStatusRegistrant != null) {
          mSmsStatusRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;
      case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        int[] smsIndex = (int[]) ret;

        if (smsIndex.length == 1) {
          if (mSmsOnSimRegistrant != null) {
            mSmsOnSimRegistrant.notifyRegistrant(new AsyncResult(null, smsIndex, null));
          }
        } else {
          if (RILJ_LOGD) riljLog(" NEW_SMS_ON_SIM ERROR with wrong length " + smsIndex.length);
        }
        break;
      case RIL_UNSOL_ON_USSD:
        String[] resp = (String[]) ret;

        if (resp.length < 2) {
          resp = new String[2];
          resp[0] = ((String[]) ret)[0];
          resp[1] = null;
        }
        if (RILJ_LOGD) unsljLogMore(response, resp[0]);
        if (mUSSDRegistrant != null) {
          mUSSDRegistrant.notifyRegistrant(new AsyncResult(null, resp, null));
        }
        break;
      case RIL_UNSOL_NITZ_TIME_RECEIVED:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        // has bonus long containing milliseconds since boot that the NITZ
        // time was received
        long nitzReceiveTime = p.readLong();

        Object[] result = new Object[2];

        String nitz = (String) ret;
        if (RILJ_LOGD)
          riljLog(" RIL_UNSOL_NITZ_TIME_RECEIVED length = " + nitz.split("[/:,+-]").length);
        // remove the tailing information that samsung added to the string
        // it will screw the NITZ parser
        if (nitz.split("[/:,+-]").length >= 9) nitz = nitz.substring(0, (nitz.lastIndexOf(",")));
        if (RILJ_LOGD) riljLog(" RIL_UNSOL_NITZ_TIME_RECEIVED striped nitz = " + nitz);
        result[0] = nitz;
        result[1] = Long.valueOf(nitzReceiveTime);

        if (mNITZTimeRegistrant != null) {

          mNITZTimeRegistrant.notifyRegistrant(new AsyncResult(null, result, null));
        } else {
          // in case NITZ time registrant isnt registered yet
          mLastNITZTimeInfo = nitz;
        }
        break;

      case RIL_UNSOL_SIGNAL_STRENGTH:
        // Note this is set to "verbose" because it happens
        // frequently
        if (RILJ_LOGV) unsljLogvRet(response, ret);

        if (mSignalStrengthRegistrant != null) {
          mSignalStrengthRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;
      case RIL_UNSOL_DATA_CALL_LIST_CHANGED:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        mDataNetworkStateRegistrants.notifyRegistrants(new AsyncResult(null, ret, null));
        break;

      case RIL_UNSOL_SUPP_SVC_NOTIFICATION:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mSsnRegistrant != null) {
          mSsnRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_STK_SESSION_END:
        if (RILJ_LOGD) unsljLog(response);

        if (mCatSessionEndRegistrant != null) {
          mCatSessionEndRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_STK_PROACTIVE_COMMAND:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mCatProCmdRegistrant != null) {
          mCatProCmdRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_STK_EVENT_NOTIFY:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mCatEventRegistrant != null) {
          mCatEventRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_STK_CALL_SETUP:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mCatCallSetUpRegistrant != null) {
          mCatCallSetUpRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_SIM_SMS_STORAGE_FULL:
        if (RILJ_LOGD) unsljLog(response);

        if (mIccSmsFullRegistrant != null) {
          mIccSmsFullRegistrant.notifyRegistrant();
        }
        break;

      case RIL_UNSOL_SIM_REFRESH:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mIccRefreshRegistrants != null) {
          mIccRefreshRegistrants.notifyRegistrants(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_CALL_RING:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mRingRegistrant != null) {
          mRingRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_RESTRICTED_STATE_CHANGED:
        if (RILJ_LOGD) unsljLogvRet(response, ret);
        if (mRestrictedStateRegistrant != null) {
          mRestrictedStateRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED:
        if (RILJ_LOGD) unsljLog(response);

        if (mIccStatusChangedRegistrants != null) {
          mIccStatusChangedRegistrants.notifyRegistrants();
        }
        break;

      case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS:
        if (RILJ_LOGD) unsljLog(response);

        SmsMessage sms = (SmsMessage) ret;

        if (mCdmaSmsRegistrant != null) {
          mCdmaSmsRegistrant.notifyRegistrant(new AsyncResult(null, sms, null));
        }
        break;

      case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS:
        if (RILJ_LOGD) unsljLog(response);

        if (mGsmBroadcastSmsRegistrant != null) {
          mGsmBroadcastSmsRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL:
        if (RILJ_LOGD) unsljLog(response);

        if (mIccSmsFullRegistrant != null) {
          mIccSmsFullRegistrant.notifyRegistrant();
        }
        break;

      case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE:
        if (RILJ_LOGD) unsljLog(response);

        if (mEmergencyCallbackModeRegistrant != null) {
          mEmergencyCallbackModeRegistrant.notifyRegistrant();
        }
        break;

      case RIL_UNSOL_CDMA_CALL_WAITING:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mCallWaitingInfoRegistrants != null) {
          mCallWaitingInfoRegistrants.notifyRegistrants(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mOtaProvisionRegistrants != null) {
          mOtaProvisionRegistrants.notifyRegistrants(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_CDMA_INFO_REC:
        ArrayList<CdmaInformationRecords> listInfoRecs;

        try {
          listInfoRecs = (ArrayList<CdmaInformationRecords>) ret;
        } catch (ClassCastException e) {
          Log.e(LOG_TAG, "Unexpected exception casting to listInfoRecs", e);
          break;
        }

        for (CdmaInformationRecords rec : listInfoRecs) {
          if (RILJ_LOGD) unsljLogRet(response, rec);
          notifyRegistrantsCdmaInfoRec(rec);
        }
        break;

      case RIL_UNSOL_OEM_HOOK_RAW:
        if (RILJ_LOGD) unsljLogvRet(response, IccUtils.bytesToHexString((byte[]) ret));
        if (mUnsolOemHookRawRegistrant != null) {
          mUnsolOemHookRawRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;

      case RIL_UNSOL_RINGBACK_TONE:
        if (RILJ_LOGD) unsljLogvRet(response, ret);
        if (mRingbackToneRegistrants != null) {
          boolean playtone = (((int[]) ret)[0] == 1);
          mRingbackToneRegistrants.notifyRegistrants(new AsyncResult(null, playtone, null));
        }
        break;

      case RIL_UNSOL_RESEND_INCALL_MUTE:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mResendIncallMuteRegistrants != null) {
          mResendIncallMuteRegistrants.notifyRegistrants(new AsyncResult(null, ret, null));
        }
    }
  }

  @Override
  protected Object responseCallList(Parcel p) {
    int num;
    int voiceSettings;
    ArrayList<DriverCall> response;
    DriverCall dc;
    int dataAvail = p.dataAvail();
    int pos = p.dataPosition();
    int size = p.dataSize();

    Log.d(LOG_TAG, "Parcel size = " + size);
    Log.d(LOG_TAG, "Parcel pos = " + pos);
    Log.d(LOG_TAG, "Parcel dataAvail = " + dataAvail);

    // Samsung f****d up here

    num = p.readInt();

    Log.d(LOG_TAG, "num = " + num);
    response = new ArrayList<DriverCall>(num);

    for (int i = 0; i < num; i++) {
      if (mIsSamsungCdma) dc = new SamsungDriverCall();
      else dc = new DriverCall();

      dc.state = DriverCall.stateFromCLCC(p.readInt());
      Log.d(LOG_TAG, "state = " + dc.state);
      dc.index = p.readInt();
      Log.d(LOG_TAG, "index = " + dc.index);
      dc.TOA = p.readInt();
      Log.d(LOG_TAG, "state = " + dc.TOA);
      dc.isMpty = (0 != p.readInt());
      Log.d(LOG_TAG, "isMpty = " + dc.isMpty);
      dc.isMT = (0 != p.readInt());
      Log.d(LOG_TAG, "isMT = " + dc.isMT);
      dc.als = p.readInt();
      Log.d(LOG_TAG, "als = " + dc.als);
      voiceSettings = p.readInt();
      dc.isVoice = (0 == voiceSettings) ? false : true;
      Log.d(LOG_TAG, "isVoice = " + dc.isVoice);
      dc.isVoicePrivacy = (0 != p.readInt());
      // Some Samsung magic data for Videocalls
      voiceSettings = p.readInt();
      // printing it to cosole for later investigation
      Log.d(LOG_TAG, "Samsung magic = " + voiceSettings);
      dc.number = p.readString();
      Log.d(LOG_TAG, "number = " + dc.number);
      int np = p.readInt();
      Log.d(LOG_TAG, "np = " + np);
      dc.numberPresentation = DriverCall.presentationFromCLIP(np);
      dc.name = p.readString();
      Log.d(LOG_TAG, "name = " + dc.name);
      dc.namePresentation = p.readInt();
      Log.d(LOG_TAG, "namePresentation = " + dc.namePresentation);
      int uusInfoPresent = p.readInt();
      Log.d(LOG_TAG, "uusInfoPresent = " + uusInfoPresent);

      if (uusInfoPresent == 1) {
        dc.uusInfo = new UUSInfo();
        dc.uusInfo.setType(p.readInt());
        dc.uusInfo.setDcs(p.readInt());
        byte[] userData = p.createByteArray();
        dc.uusInfo.setUserData(userData);
        Log.v(
            LOG_TAG,
            String.format(
                "Incoming UUS : type=%d, dcs=%d, length=%d",
                dc.uusInfo.getType(), dc.uusInfo.getDcs(), dc.uusInfo.getUserData().length));
        Log.v(LOG_TAG, "Incoming UUS : data (string)=" + new String(dc.uusInfo.getUserData()));
        Log.v(
            LOG_TAG,
            "Incoming UUS : data (hex): " + IccUtils.bytesToHexString(dc.uusInfo.getUserData()));
      } else {
        Log.v(LOG_TAG, "Incoming UUS : NOT present!");
      }

      // Make sure there's a leading + on addresses with a TOA of 145
      dc.number = PhoneNumberUtils.stringFromStringAndTOA(dc.number, dc.TOA);

      response.add(dc);

      if (dc.isVoicePrivacy) {
        mVoicePrivacyOnRegistrants.notifyRegistrants();
        Log.d(LOG_TAG, "InCall VoicePrivacy is enabled");
      } else {
        mVoicePrivacyOffRegistrants.notifyRegistrants();
        Log.d(LOG_TAG, "InCall VoicePrivacy is disabled");
      }
    }

    Collections.sort(response);

    return response;
  }

  @Override
  protected Object responseSignalStrength(Parcel p) {
    int numInts = 12;
    int response[];

    /* TODO: Add SignalStrength class to match RIL_SignalStrength */
    response = new int[numInts];
    for (int i = 0; i < 7; i++) {
      response[i] = p.readInt();
    }
    // SamsungRIL is a v3 RIL, fill the rest with -1
    for (int i = 7; i < numInts; i++) {
      response[i] = -1;
    }

    /* Matching Samsung signal strength to asu.
    Method taken from Samsungs cdma/gsmSignalStateTracker */
    if (mSignalbarCount) {
      // Samsung sends the count of bars that should be displayed instead of
      // a real signal strength
      response[0] = ((response[0] & 0xFF00) >> 8) * 3; // gsmDbm
    } else {
      response[0] = response[0] & 0xFF; // gsmDbm
    }
    response[1] = -1; // gsmEcio
    response[2] = (response[2] < 0) ? -120 : -response[2]; // cdmaDbm
    response[3] = (response[3] < 0) ? -160 : -response[3]; // cdmaEcio
    response[4] = (response[4] < 0) ? -120 : -response[4]; // evdoRssi
    response[5] = (response[5] < 0) ? -1 : -response[5]; // evdoEcio
    if (response[6] < 0 || response[6] > 8) response[6] = -1;

    return response;
  }

  protected Object responseNetworkType(Parcel p) {
    int response[] = (int[]) responseInts(p);

    // When the modem responds Phone.NT_MODE_GLOBAL, it means Phone.NT_MODE_WCDMA_PREF
    if (!mIsSamsungCdma && response[0] == Phone.NT_MODE_GLOBAL) {
      Log.d(LOG_TAG, "Overriding network type response from global to WCDMA preferred");
      response[0] = Phone.NT_MODE_WCDMA_PREF;
    }

    return response;
  }

  @Override
  protected Object responseSetupDataCall(Parcel p) {
    DataCallState dataCall = new DataCallState();
    String strings[] = (String[]) responseStrings(p);

    if (strings.length >= 2) {
      dataCall.cid = Integer.parseInt(strings[0]);
      dataCall.ifname = strings[1];

      if (strings.length >= 3) {
        dataCall.addresses = strings[2].split(" ");
      }
    } else {
      dataCall.status = FailCause.ERROR_UNSPECIFIED.getErrorCode(); // Who knows?
    }

    return dataCall;
  }

  protected class SamsungDriverCall extends DriverCall {
    @Override
    public String toString() {
      // Samsung CDMA devices' call parcel is formatted differently
      // fake unused data for video calls, and fix formatting
      // so that voice calls' information can be correctly parsed
      return "id="
          + index
          + ","
          + state
          + ","
          + "toa="
          + TOA
          + ","
          + (isMpty ? "conf" : "norm")
          + ","
          + (isMT ? "mt" : "mo")
          + ","
          + "als="
          + als
          + ","
          + (isVoice ? "voc" : "nonvoc")
          + ","
          + "nonvid"
          + ","
          + number
          + ","
          + "cli="
          + numberPresentation
          + ","
          + "name="
          + name
          + ","
          + namePresentation;
    }
  }

  /** {@inheritDoc} */
  @Override
  public void setCurrentPreferredNetworkType() {
    if (RILJ_LOGD) riljLog("setCurrentPreferredNetworkType IGNORED");
    /* Google added this as a fix for crespo loosing network type after
     * taking an OTA. This messes up the data connection state for us
     * due to the way we handle network type change (disable data
     * then change then re-enable).
     */
  }

  @Override
  public void setPreferredNetworkType(int networkType, Message response) {
    /* Samsung modem implementation does bad things when a datacall is running
     * while switching the preferred networktype.
     */
    ConnectivityManager cm =
        (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm.getMobileDataEnabled()) {
      ConnectivityHandler handler = new ConnectivityHandler(mContext);
      handler.setPreferedNetworkType(networkType, response);
    } else {
      sendPreferedNetworktype(networkType, response);
    }
  }

  // Sends the real RIL request to the modem.
  private void sendPreferedNetworktype(int networkType, Message response) {
    RILRequest rr =
        RILRequest.obtain(RILConstants.RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE, response);

    rr.mp.writeInt(1);
    rr.mp.writeInt(networkType);

    if (RILJ_LOGD)
      riljLog(rr.serialString() + "> " + requestToString(rr.mRequest) + " : " + networkType);

    send(rr);
  }
  /* private class that does the handling for the dataconnection
   * dataconnection is done async, so we send the request for disabling it,
   * wait for the response, set the prefered networktype and notify the
   * real sender with its result.
   */
  private class ConnectivityHandler extends Handler {

    private static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 30;
    private Context mContext;
    private int mDesiredNetworkType;
    // the original message, we need it for calling back the original caller when done
    private Message mNetworktypeResponse;
    private ConnectivityBroadcastReceiver mConnectivityReceiver =
        new ConnectivityBroadcastReceiver();

    public ConnectivityHandler(Context context) {
      mContext = context;
    }

    private void startListening() {
      IntentFilter filter = new IntentFilter();
      filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
      mContext.registerReceiver(mConnectivityReceiver, filter);
    }

    private synchronized void stopListening() {
      mContext.unregisterReceiver(mConnectivityReceiver);
    }

    public void setPreferedNetworkType(int networkType, Message response) {
      Log.d(LOG_TAG, "Mobile Dataconnection is online setting it down");
      mDesiredNetworkType = networkType;
      mNetworktypeResponse = response;
      ConnectivityManager cm =
          (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
      // start listening for the connectivity change broadcast
      startListening();
      cm.setMobileDataEnabled(false);
    }

    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
          // networktype was set, now we can enable the dataconnection again
        case MESSAGE_SET_PREFERRED_NETWORK_TYPE:
          ConnectivityManager cm =
              (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

          Log.d(LOG_TAG, "preferred NetworkType set upping Mobile Dataconnection");

          cm.setMobileDataEnabled(true);
          // everything done now call back that we have set the networktype
          AsyncResult.forMessage(mNetworktypeResponse, null, null);
          mNetworktypeResponse.sendToTarget();
          mNetworktypeResponse = null;
          break;
        default:
          throw new RuntimeException("unexpected event not handled");
      }
    }

    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
          Log.w(LOG_TAG, "onReceived() called with " + intent);
          return;
        }
        boolean noConnectivity =
            intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

        if (noConnectivity) {
          // Ok dataconnection is down, now set the networktype
          Log.w(LOG_TAG, "Mobile Dataconnection is now down setting preferred NetworkType");
          stopListening();
          sendPreferedNetworktype(
              mDesiredNetworkType, obtainMessage(MESSAGE_SET_PREFERRED_NETWORK_TYPE));
          mDesiredNetworkType = -1;
        }
      }
    }
  }
}
  private static boolean containsPluginPermissionAndSignatures(PackageInfo pkgInfo) {

    // check if the plugin has the required permissions
    String permissions[] = pkgInfo.requestedPermissions;
    if (permissions == null) {
      return false;
    }
    boolean permissionOk = false;
    for (String permit : permissions) {
      if (PLUGIN_PERMISSION.equals(permit)) {
        permissionOk = true;
        break;
      }
    }
    if (!permissionOk) {
      return false;
    }

    // check to ensure the plugin is properly signed
    Signature signatures[] = pkgInfo.signatures;
    if (signatures == null) {
      return false;
    }

    if ((SystemProperties.getBoolean("ro.secure", false))
        && !((pkgInfo.packageName.equals("com.amlogic.plugins.BestvAuthPlugin")
            && (SystemProperties.getBoolean("ro.BestvPlugin.sigbypass", true))))
        && !((pkgInfo.packageName.equals("com.amlogic.plugins.BestvMediaPlugin")
            && (SystemProperties.getBoolean("ro.BestvPlugin.sigbypass", true))))
        && !((pkgInfo.packageName.equals("com.adobe.flashplayer")
            && (SystemProperties.getBoolean("ro.flashplayer.sigbypass", true))))) {
      boolean signatureMatch = false;
      for (Signature signature : signatures) {
        for (int i = 0; i < SIGNATURES.length; i++) {
          if (SIGNATURES[i].equals(signature)) {
            signatureMatch = true;
            break;
          }
        }
      }
      if (!signatureMatch) {
        return false;
      }
    }

    // block official Adobe Flash plug-in
    if (pkgInfo.packageName.equals("com.adobe.flashplayer")) {
      boolean signatureMatch = false;
      for (Signature signature : signatures) {
        for (int i = 0; i < SIGNATURES.length; i++) {
          if (SIGNATURES[i].equals(signature)) {
            signatureMatch = true;
            break;
          }
        }
      }
      if (signatureMatch) {
        return false;
      }
    }

    return true;
  }
public class SamsungExynos4RIL extends RIL implements CommandsInterface {

  // SAMSUNG STATES
  static final int RIL_REQUEST_GET_CELL_BROADCAST_CONFIG = 10002;

  static final int RIL_REQUEST_SEND_ENCODED_USSD = 10005;
  static final int RIL_REQUEST_SET_PDA_MEMORY_STATUS = 10006;
  static final int RIL_REQUEST_GET_PHONEBOOK_STORAGE_INFO = 10007;
  static final int RIL_REQUEST_GET_PHONEBOOK_ENTRY = 10008;
  static final int RIL_REQUEST_ACCESS_PHONEBOOK_ENTRY = 10009;
  static final int RIL_REQUEST_DIAL_VIDEO_CALL = 10010;
  static final int RIL_REQUEST_CALL_DEFLECTION = 10011;
  static final int RIL_REQUEST_READ_SMS_FROM_SIM = 10012;
  static final int RIL_REQUEST_USIM_PB_CAPA = 10013;
  static final int RIL_REQUEST_LOCK_INFO = 10014;

  static final int RIL_REQUEST_DIAL_EMERGENCY = 10016;
  static final int RIL_REQUEST_GET_STOREAD_MSG_COUNT = 10017;
  static final int RIL_REQUEST_STK_SIM_INIT_EVENT = 10018;
  static final int RIL_REQUEST_GET_LINE_ID = 10019;
  static final int RIL_REQUEST_SET_LINE_ID = 10020;
  static final int RIL_REQUEST_GET_SERIAL_NUMBER = 10021;
  static final int RIL_REQUEST_GET_MANUFACTURE_DATE_NUMBER = 10022;
  static final int RIL_REQUEST_GET_BARCODE_NUMBER = 10023;
  static final int RIL_REQUEST_UICC_GBA_AUTHENTICATE_BOOTSTRAP = 10024;
  static final int RIL_REQUEST_UICC_GBA_AUTHENTICATE_NAF = 10025;
  static final int RIL_REQUEST_SIM_TRANSMIT_BASIC = 10026;
  static final int RIL_REQUEST_SIM_OPEN_CHANNEL = 10027;
  static final int RIL_REQUEST_SIM_CLOSE_CHANNEL = 10028;
  static final int RIL_REQUEST_SIM_TRANSMIT_CHANNEL = 10029;
  static final int RIL_REQUEST_SIM_AUTH = 10030;
  static final int RIL_REQUEST_PS_ATTACH = 10031;
  static final int RIL_REQUEST_PS_DETACH = 10032;
  static final int RIL_REQUEST_ACTIVATE_DATA_CALL = 10033;
  static final int RIL_REQUEST_CHANGE_SIM_PERSO = 10034;
  static final int RIL_REQUEST_ENTER_SIM_PERSO = 10035;
  static final int RIL_REQUEST_GET_TIME_INFO = 10036;
  static final int RIL_REQUEST_OMADM_SETUP_SESSION = 10037;
  static final int RIL_REQUEST_OMADM_SERVER_START_SESSION = 10038;
  static final int RIL_REQUEST_OMADM_CLIENT_START_SESSION = 10039;
  static final int RIL_REQUEST_OMADM_SEND_DATA = 10040;
  static final int RIL_REQUEST_CDMA_GET_DATAPROFILE = 10041;
  static final int RIL_REQUEST_CDMA_SET_DATAPROFILE = 10042;
  static final int RIL_REQUEST_CDMA_GET_SYSTEMPROPERTIES = 10043;
  static final int RIL_REQUEST_CDMA_SET_SYSTEMPROPERTIES = 10044;
  static final int RIL_REQUEST_SEND_SMS_COUNT = 10045;
  static final int RIL_REQUEST_SEND_SMS_MSG = 10046;
  static final int RIL_REQUEST_SEND_SMS_MSG_READ_STATUS = 10047;
  static final int RIL_REQUEST_MODEM_HANGUP = 10048;
  static final int RIL_REQUEST_SET_SIM_POWER = 10049;
  static final int RIL_REQUEST_SET_PREFERRED_NETWORK_LIST = 10050;
  static final int RIL_REQUEST_GET_PREFERRED_NETWORK_LIST = 10051;
  static final int RIL_REQUEST_HANGUP_VT = 10052;

  static final int RIL_UNSOL_RELEASE_COMPLETE_MESSAGE = 11001;
  static final int RIL_UNSOL_STK_SEND_SMS_RESULT = 11002;
  static final int RIL_UNSOL_STK_CALL_CONTROL_RESULT = 11003;
  static final int RIL_UNSOL_DUN_CALL_STATUS = 11004;

  static final int RIL_UNSOL_O2_HOME_ZONE_INFO = 11007;
  static final int RIL_UNSOL_DEVICE_READY_NOTI = 11008;
  static final int RIL_UNSOL_GPS_NOTI = 11009;
  static final int RIL_UNSOL_AM = 11010;
  static final int RIL_UNSOL_DUN_PIN_CONTROL_SIGNAL = 11011;
  static final int RIL_UNSOL_DATA_SUSPEND_RESUME = 11012;
  static final int RIL_UNSOL_SAP = 11013;

  static final int RIL_UNSOL_SIM_SMS_STORAGE_AVAILALE = 11015;
  static final int RIL_UNSOL_HSDPA_STATE_CHANGED = 11016;
  static final int RIL_UNSOL_WB_AMR_STATE = 11017;
  static final int RIL_UNSOL_TWO_MIC_STATE = 11018;
  static final int RIL_UNSOL_DHA_STATE = 11019;
  static final int RIL_UNSOL_UART = 11020;
  static final int RIL_UNSOL_RESPONSE_HANDOVER = 11021;
  static final int RIL_UNSOL_IPV6_ADDR = 11022;
  static final int RIL_UNSOL_NWK_INIT_DISC_REQUEST = 11023;
  static final int RIL_UNSOL_RTS_INDICATION = 11024;
  static final int RIL_UNSOL_OMADM_SEND_DATA = 11025;
  static final int RIL_UNSOL_DUN = 11026;
  static final int RIL_UNSOL_SYSTEM_REBOOT = 11027;
  static final int RIL_UNSOL_VOICE_PRIVACY_CHANGED = 11028;
  static final int RIL_UNSOL_UTS_GETSMSCOUNT = 11029;
  static final int RIL_UNSOL_UTS_GETSMSMSG = 11030;
  static final int RIL_UNSOL_UTS_GET_UNREAD_SMS_STATUS = 11031;
  static final int RIL_UNSOL_MIP_CONNECT_STATUS = 11032;

  protected HandlerThread mSamsungExynos4RILThread;
  protected ConnectivityHandler mSamsungExynos4RILHandler;
  private AudioManager audioManager;
  private boolean mIsGBModem = SystemProperties.getBoolean("ro.ril.gbmodem", false);

  public SamsungExynos4RIL(Context context, int networkMode, int cdmaSubscription) {
    super(context, networkMode, cdmaSubscription);
    audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    mQANElements = 5;
  }

  static String requestToString(int request) {
    switch (request) {
      case RIL_REQUEST_DIAL_EMERGENCY:
        return "DIAL_EMERGENCY";
      default:
        return RIL.requestToString(request);
    }
  }

  @Override
  public void setCurrentPreferredNetworkType() {
    if (RILJ_LOGD) riljLog("setCurrentPreferredNetworkType IGNORED");
    /* Google added this as a fix for crespo loosing network type after
     * taking an OTA. This messes up the data connection state for us
     * due to the way we handle network type change (disable data
     * then change then re-enable).
     */
  }

  private boolean NeedReconnect() {
    ConnectivityManager cm =
        (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni_active = cm.getActiveNetworkInfo();

    return ni_active != null
        && ni_active.getTypeName().equalsIgnoreCase("mobile")
        && ni_active.isConnected()
        && cm.getMobileDataEnabled();
  }

  @Override
  public void setPreferredNetworkType(int networkType, Message response) {
    /* Samsung modem implementation does bad things when a datacall is running
     * while switching the preferred networktype.
     */
    HandlerThread handlerThread;
    Looper looper;

    if (NeedReconnect()) {
      if (mSamsungExynos4RILHandler == null) {

        handlerThread = new HandlerThread("mSamsungExynos4RILThread");
        mSamsungExynos4RILThread = handlerThread;

        mSamsungExynos4RILThread.start();

        looper = mSamsungExynos4RILThread.getLooper();
        mSamsungExynos4RILHandler = new ConnectivityHandler(mContext, looper);
      }
      mSamsungExynos4RILHandler.setPreferedNetworkType(networkType, response);
    } else {
      if (mSamsungExynos4RILHandler != null) {
        mSamsungExynos4RILThread = null;
        mSamsungExynos4RILHandler = null;
      }
      sendPreferedNetworktype(networkType, response);
    }
  }

  // Sends the real RIL request to the modem.
  private void sendPreferedNetworktype(int networkType, Message response) {
    RILRequest rr =
        RILRequest.obtain(RILConstants.RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE, response);

    rr.mp.writeInt(1);
    rr.mp.writeInt(networkType);

    if (RILJ_LOGD)
      riljLog(rr.serialString() + "> " + requestToString(rr.mRequest) + " : " + networkType);

    send(rr);
  }

  /* private class that does the handling for the dataconnection
   * dataconnection is done async, so we send the request for disabling it,
   * wait for the response, set the prefered networktype and notify the
   * real sender with its result.
   */
  private class ConnectivityHandler extends Handler {

    private static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 30;
    private Context mContext;
    private int mDesiredNetworkType;
    // the original message, we need it for calling back the original caller when done
    private Message mNetworktypeResponse;
    private ConnectivityBroadcastReceiver mConnectivityReceiver =
        new ConnectivityBroadcastReceiver();

    public ConnectivityHandler(Context context, Looper looper) {
      super(looper);
      mContext = context;
    }

    private void startListening() {
      IntentFilter filter = new IntentFilter();
      filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
      mContext.registerReceiver(mConnectivityReceiver, filter);
    }

    private synchronized void stopListening() {
      mContext.unregisterReceiver(mConnectivityReceiver);
    }

    public void setPreferedNetworkType(int networkType, Message response) {
      Log.d(LOG_TAG, "Mobile Dataconnection is online setting it down");
      mDesiredNetworkType = networkType;
      mNetworktypeResponse = response;
      ConnectivityManager cm =
          (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
      // start listening for the connectivity change broadcast
      startListening();
      cm.setMobileDataEnabled(false);
    }

    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
          // networktype was set, now we can enable the dataconnection again
        case MESSAGE_SET_PREFERRED_NETWORK_TYPE:
          ConnectivityManager cm =
              (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

          Log.d(LOG_TAG, "preferred NetworkType set upping Mobile Dataconnection");
          cm.setMobileDataEnabled(true);
          // everything done now call back that we have set the networktype
          AsyncResult.forMessage(mNetworktypeResponse, null, null);
          mNetworktypeResponse.sendToTarget();
          mNetworktypeResponse = null;
          break;
        default:
          throw new RuntimeException("unexpected event not handled");
      }
    }

    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
          Log.w(LOG_TAG, "onReceived() called with " + intent);
          return;
        }
        boolean noConnectivity =
            intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

        if (noConnectivity) {
          // Ok dataconnection is down, now set the networktype
          Log.w(LOG_TAG, "Mobile Dataconnection is now down setting preferred NetworkType");
          stopListening();
          sendPreferedNetworktype(
              mDesiredNetworkType, obtainMessage(MESSAGE_SET_PREFERRED_NETWORK_TYPE));
          mDesiredNetworkType = -1;
        }
      }
    }
  }

  @Override
  protected RILRequest findAndRemoveRequestFromList(int serial) {
    long removalTime = System.currentTimeMillis();
    long timeDiff = 0;

    synchronized (mRequestsList) {
      Iterator<RILRequest> itr = mRequestsList.iterator();

      while (itr.hasNext()) {
        RILRequest rr = itr.next();

        if (rr.mSerial == serial) {
          itr.remove();
          if (mRequestMessagesWaiting > 0) mRequestMessagesWaiting--;
          return rr;
        } else {
          // We need some special code here for the Samsung RIL,
          // which isn't responding to some requests.
          // We will print a list of such stale requests which
          // haven't yet received a response. If the timeout fires
          // first, then the wakelock is released without debugging.
          timeDiff = removalTime - rr.creationTime;
          if (timeDiff > mWakeLockTimeout) {
            Log.d(
                LOG_TAG,
                "No response for ["
                    + rr.mSerial
                    + "] "
                    + requestToString(rr.mRequest)
                    + " after "
                    + timeDiff
                    + " milliseconds.");

            /* Don't actually remove anything for now. Consider uncommenting this to
            purge stale requests */

            /*
            itr.remove();
            if (mRequestMessagesWaiting > 0) {
                mRequestMessagesWaiting--;
            }

            // We don't handle the callback (ie. rr.mResult) for
            // RIL_REQUEST_SET_TTY_MODE, which is
            // RIL_REQUEST_QUERY_TTY_MODE. The reason for not doing
            // so is because it will also not get a response from the
            // Samsung RIL
            rr.release();
            */
          }
        }
      }
    }
    return null;
  }

  @Override
  protected void processSolicited(Parcel p) {
    int serial, error;
    boolean found = false;

    serial = p.readInt();
    error = p.readInt();

    RILRequest rr;

    rr = findAndRemoveRequestFromList(serial);

    if (rr == null) {
      Log.w(LOG_TAG, "Unexpected solicited response! sn: " + serial + " error: " + error);
      return;
    }

    Object ret = null;

    if (error == 0 || p.dataAvail() > 0) {
      // either command succeeds or command fails but with data payload
      try {
        switch (rr.mRequest) {
          case RIL_REQUEST_GET_SIM_STATUS:
            ret = responseIccCardStatus(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PIN:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PUK:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PIN2:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_SIM_PUK2:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CHANGE_SIM_PIN:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CHANGE_SIM_PIN2:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_GET_CURRENT_CALLS:
            ret = responseCallList(p);
            break;
          case RIL_REQUEST_DIAL:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_IMSI:
            ret = responseString(p);
            break;
          case RIL_REQUEST_HANGUP:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CONFERENCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_UDUB:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_LAST_CALL_FAIL_CAUSE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SIGNAL_STRENGTH:
            ret = responseSignalStrength(p);
            break;
          case RIL_REQUEST_VOICE_REGISTRATION_STATE:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_DATA_REGISTRATION_STATE:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_OPERATOR:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_RADIO_POWER:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DTMF:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SEND_SMS:
            ret = responseSMS(p);
            break;
          case RIL_REQUEST_SEND_SMS_EXPECT_MORE:
            ret = responseSMS(p);
            break;
          case RIL_REQUEST_SETUP_DATA_CALL:
            ret = responseSetupDataCall(p);
            break;
          case RIL_REQUEST_SIM_IO:
            ret = responseICC_IO(p);
            break;
          case RIL_REQUEST_SEND_USSD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CANCEL_USSD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_CLIR:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_CLIR:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS:
            ret = responseCallForward(p);
            break;
          case RIL_REQUEST_SET_CALL_FORWARD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_CALL_WAITING:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_CALL_WAITING:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SMS_ACKNOWLEDGE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_IMEI:
            ret = responseString(p);
            break;
          case RIL_REQUEST_GET_IMEISV:
            ret = responseString(p);
            break;
          case RIL_REQUEST_ANSWER:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DEACTIVATE_DATA_CALL:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_FACILITY_LOCK:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_FACILITY_LOCK:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CHANGE_BARRING_PASSWORD:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS:
            ret = responseOperatorInfos(p);
            break;
          case RIL_REQUEST_DTMF_START:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DTMF_STOP:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_BASEBAND_VERSION:
            ret = responseString(p);
            break;
          case RIL_REQUEST_SEPARATE_CONNECTION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_MUTE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_MUTE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_QUERY_CLIP:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_DATA_CALL_LIST:
            ret = responseDataCallList(p);
            break;
          case RIL_REQUEST_RESET_RADIO:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_OEM_HOOK_RAW:
            ret = responseRaw(p);
            break;
          case RIL_REQUEST_OEM_HOOK_STRINGS:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_SCREEN_STATE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_SUPP_SVC_NOTIFICATION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_WRITE_SMS_TO_SIM:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_DELETE_SMS_ON_SIM:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_BAND_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_STK_GET_PROFILE:
            ret = responseString(p);
            break;
          case RIL_REQUEST_STK_SET_PROFILE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND:
            ret = responseString(p);
            break;
          case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_EXPLICIT_CALL_TRANSFER:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE:
            ret = responseGetPreferredNetworkType(p);
            break;
          case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS:
            ret = responseCellList(p);
            break;
          case RIL_REQUEST_SET_LOCATION_UPDATES:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_SET_TTY_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_QUERY_TTY_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CDMA_FLASH:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_BURST_DTMF:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SEND_SMS:
            ret = responseSMS(p);
            break;
          case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GSM_GET_BROADCAST_CONFIG:
            ret = responseGmsBroadcastConfig(p);
            break;
          case RIL_REQUEST_GSM_SET_BROADCAST_CONFIG:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_GSM_BROADCAST_ACTIVATION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_GET_BROADCAST_CONFIG:
            ret = responseCdmaBroadcastConfig(p);
            break;
          case RIL_REQUEST_CDMA_SET_BROADCAST_CONFIG:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_BROADCAST_ACTIVATION:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_SUBSCRIPTION:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_DEVICE_IDENTITY:
            ret = responseStrings(p);
            break;
          case RIL_REQUEST_GET_SMSC_ADDRESS:
            ret = responseString(p);
            break;
          case RIL_REQUEST_SET_SMSC_ADDRESS:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_ISIM_AUTHENTICATION:
            ret = responseString(p);
            break;
          case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU:
            ret = responseVoid(p);
            break;
          case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS:
            ret = responseICC_IO(p);
            break;
          case RIL_REQUEST_VOICE_RADIO_TECH:
            ret = responseInts(p);
            break;
          case RIL_REQUEST_DIAL_EMERGENCY:
            ret = responseVoid(p);
            break;
          default:
            throw new RuntimeException("Unrecognized solicited response: " + rr.mRequest);
            // break;
        }
      } catch (Throwable tr) {
        // Exceptions here usually mean invalid RIL responses

        Log.w(
            LOG_TAG,
            rr.serialString()
                + "< "
                + requestToString(rr.mRequest)
                + " exception, possible invalid RIL response",
            tr);

        if (rr.mResult != null) {
          AsyncResult.forMessage(rr.mResult, null, tr);
          rr.mResult.sendToTarget();
        }
        rr.release();
        return;
      }
    }

    if (error != 0) {
      // ugly fix for Samsung messing up SMS_SEND request fail in binary RIL
      if (!(error == -1 && rr.mRequest == RIL_REQUEST_SEND_SMS)) {
        rr.onError(error, ret);
        rr.release();
        return;
      } else {
        try {
          ret = responseSMS(p);
        } catch (Throwable tr) {
          Log.w(
              LOG_TAG,
              rr.serialString()
                  + "< "
                  + requestToString(rr.mRequest)
                  + " exception, Processing Samsung SMS fix ",
              tr);
          rr.onError(error, ret);
          rr.release();
          return;
        }
      }
    }

    if (RILJ_LOGD)
      riljLog(
          rr.serialString()
              + "< "
              + requestToString(rr.mRequest)
              + " "
              + retToString(rr.mRequest, ret));

    if (rr.mResult != null) {
      AsyncResult.forMessage(rr.mResult, ret, null);
      rr.mResult.sendToTarget();
    }

    rr.release();
  }

  @Override
  public void dial(String address, int clirMode, UUSInfo uusInfo, Message result) {
    RILRequest rr;
    if (PhoneNumberUtils.isEmergencyNumber(address)) {
      dialEmergencyCall(address, clirMode, result);
      return;
    }

    rr = RILRequest.obtain(RIL_REQUEST_DIAL, result);
    rr.mp.writeString(address);
    rr.mp.writeInt(clirMode);
    rr.mp.writeInt(0); // UUS information is absent

    if (uusInfo == null) {
      rr.mp.writeInt(0); // UUS information is absent
    } else {
      rr.mp.writeInt(1); // UUS information is present
      rr.mp.writeInt(uusInfo.getType());
      rr.mp.writeInt(uusInfo.getDcs());
      rr.mp.writeByteArray(uusInfo.getUserData());
    }

    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));

    send(rr);
  }

  public void dialEmergencyCall(String address, int clirMode, Message result) {
    RILRequest rr;
    Log.v(LOG_TAG, "Emergency dial: " + address);

    rr = RILRequest.obtain(RIL_REQUEST_DIAL_EMERGENCY, result);
    rr.mp.writeString(address + "/");
    rr.mp.writeInt(clirMode);
    rr.mp.writeInt(0);
    rr.mp.writeInt(0);

    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));

    send(rr);
  }

  @Override
  protected void processUnsolicited(Parcel p) {
    Object ret;
    int dataPosition = p.dataPosition();
    int response = p.readInt();

    switch (response) {
      case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
        ret = responseVoid(p);
        break;
      case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS:
        ret = responseString(p);
        break;
      case RIL_UNSOL_RIL_CONNECTED:
        ret = responseInts(p);
        break;
        // SAMSUNG STATES
      case RIL_UNSOL_AM:
        ret = responseString(p);
        break;
      case RIL_UNSOL_DUN_PIN_CONTROL_SIGNAL:
        ret = responseVoid(p);
        break;
      case RIL_UNSOL_DATA_SUSPEND_RESUME:
        ret = responseInts(p);
        break;
      case RIL_UNSOL_STK_CALL_CONTROL_RESULT:
        ret = responseVoid(p);
        break;
      case RIL_UNSOL_TWO_MIC_STATE:
        ret = responseInts(p);
        break;
      case RIL_UNSOL_WB_AMR_STATE:
        ret = responseInts(p);
        break;

      default:
        // Rewind the Parcel
        p.setDataPosition(dataPosition);

        // Forward responses that we are not overriding to the super class
        super.processUnsolicited(p);
        return;
    }

    switch (response) {
      case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
        /* has bonus radio state int */
        int state = p.readInt();
        Log.d(LOG_TAG, "Radio state: " + state);

        switch (state) {
          case 2:
            // RADIO_UNAVAILABLE
            state = 1;
            break;
          case 3:
            // RADIO_ON
            state = 10;
            break;
          case 4:
            // RADIO_ON
            state = 10;
            // When SIM is PIN-unlocked, RIL doesn't respond with
            // RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED.
            // We notify the system here.
            Log.d(LOG_TAG, "SIM is PIN-unlocked now");
            if (mIccStatusChangedRegistrants != null) {
              mIccStatusChangedRegistrants.notifyRegistrants();
            }
            break;
        }
        RadioState newState = getRadioStateFromInt(state);
        Log.d(LOG_TAG, "New Radio state: " + state + " (" + newState.toString() + ")");
        switchToRadioState(newState);
        break;
      case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        if (mGsmBroadcastSmsRegistrant != null) {
          mGsmBroadcastSmsRegistrant.notifyRegistrant(new AsyncResult(null, ret, null));
        }
        break;
      case RIL_UNSOL_RIL_CONNECTED:
        if (RILJ_LOGD) unsljLogRet(response, ret);

        // Initial conditions
        setRadioPower(false, null);
        sendPreferedNetworktype(mPreferredNetworkType, null);
        setCdmaSubscriptionSource(mCdmaSubscription, null);
        notifyRegistrantsRilConnectionChanged(((int[]) ret)[0]);
        break;
        // SAMSUNG STATES
      case RIL_UNSOL_AM:
        if (RILJ_LOGD) samsungUnsljLogRet(response, ret);
        String amString = (String) ret;
        Log.d(LOG_TAG, "Executing AM: " + amString);

        try {
          Runtime.getRuntime().exec("am " + amString);
        } catch (IOException e) {
          e.printStackTrace();
          Log.e(LOG_TAG, "am " + amString + " could not be executed.");
        }
        break;
      case RIL_UNSOL_DUN_PIN_CONTROL_SIGNAL:
        if (RILJ_LOGD) samsungUnsljLogRet(response, ret);
        break;
      case RIL_UNSOL_DATA_SUSPEND_RESUME:
        if (RILJ_LOGD) samsungUnsljLogRet(response, ret);
        break;
      case RIL_UNSOL_STK_CALL_CONTROL_RESULT:
        if (RILJ_LOGD) samsungUnsljLogRet(response, ret);
        break;
      case RIL_UNSOL_TWO_MIC_STATE:
        if (RILJ_LOGD) samsungUnsljLogRet(response, ret);
        break;
      case RIL_UNSOL_WB_AMR_STATE:
        if (RILJ_LOGD) samsungUnsljLogRet(response, ret);
        setWbAmr(((int[]) ret)[0]);
        break;
    }
  }

  static String samsungResponseToString(int request) {
    switch (request) {
        // SAMSUNG STATES
      case RIL_UNSOL_AM:
        return "RIL_UNSOL_AM";
      case RIL_UNSOL_DUN_PIN_CONTROL_SIGNAL:
        return "RIL_UNSOL_DUN_PIN_CONTROL_SIGNAL";
      case RIL_UNSOL_DATA_SUSPEND_RESUME:
        return "RIL_UNSOL_DATA_SUSPEND_RESUME";
      case RIL_UNSOL_STK_CALL_CONTROL_RESULT:
        return "RIL_UNSOL_STK_CALL_CONTROL_RESULT";
      case RIL_UNSOL_TWO_MIC_STATE:
        return "RIL_UNSOL_TWO_MIC_STATE";
      case RIL_UNSOL_WB_AMR_STATE:
        return "RIL_UNSOL_WB_AMR_STATE";
      default:
        return "<unknown response: " + request + ">";
    }
  }

  protected void samsungUnsljLog(int response) {
    riljLog("[UNSL]< " + samsungResponseToString(response));
  }

  protected void samsungUnsljLogMore(int response, String more) {
    riljLog("[UNSL]< " + samsungResponseToString(response) + " " + more);
  }

  protected void samsungUnsljLogRet(int response, Object ret) {
    riljLog("[UNSL]< " + samsungResponseToString(response) + " " + retToString(response, ret));
  }

  protected void samsungUnsljLogvRet(int response, Object ret) {
    riljLogv("[UNSL]< " + samsungResponseToString(response) + " " + retToString(response, ret));
  }

  /**
   * Notifiy all registrants that the ril has connected or disconnected.
   *
   * @param rilVer is the version of the ril or -1 if disconnected.
   */
  private void notifyRegistrantsRilConnectionChanged(int rilVer) {
    mRilVersion = rilVer;
    if (mRilConnectedRegistrants != null) {
      mRilConnectedRegistrants.notifyRegistrants(new AsyncResult(null, new Integer(rilVer), null));
    }
  }

  /**
   * Set audio parameter "wb_amr" for HD-Voice (Wideband AMR).
   *
   * @param state: 0 = unsupported, 1 = supported.
   */
  private void setWbAmr(int state) {
    if (state == 1) {
      Log.d(LOG_TAG, "setWbAmr(): setting audio parameter - wb_amr=on");
      audioManager.setParameters("wb_amr=on");
    } else {
      Log.d(LOG_TAG, "setWbAmr(): setting audio parameter - wb_amr=off");
      audioManager.setParameters("wb_amr=off");
    }
  }

  @Override
  protected Object responseCallList(Parcel p) {
    int num;
    boolean isVideo;
    ArrayList<DriverCall> response;
    DriverCall dc;
    int dataAvail = p.dataAvail();
    int pos = p.dataPosition();
    int size = p.dataSize();

    Log.d(LOG_TAG, "Parcel size = " + size);
    Log.d(LOG_TAG, "Parcel pos = " + pos);
    Log.d(LOG_TAG, "Parcel dataAvail = " + dataAvail);

    // Samsung changes
    num = p.readInt();

    Log.d(LOG_TAG, "num = " + num);
    response = new ArrayList<DriverCall>(num);

    for (int i = 0; i < num; i++) {

      dc = new DriverCall();
      dc.state = DriverCall.stateFromCLCC(p.readInt());
      dc.index = p.readInt();
      dc.TOA = p.readInt();
      dc.isMpty = (0 != p.readInt());
      dc.isMT = (0 != p.readInt());
      dc.als = p.readInt();
      dc.isVoice = (0 != p.readInt());
      isVideo = (0 != p.readInt());
      dc.isVoicePrivacy = (0 != p.readInt());
      dc.number = p.readString();
      int np = p.readInt();
      dc.numberPresentation = DriverCall.presentationFromCLIP(np);
      dc.name = p.readString();
      dc.namePresentation = p.readInt();
      int uusInfoPresent = p.readInt();

      Log.d(LOG_TAG, "state = " + dc.state);
      Log.d(LOG_TAG, "index = " + dc.index);
      Log.d(LOG_TAG, "state = " + dc.TOA);
      Log.d(LOG_TAG, "isMpty = " + dc.isMpty);
      Log.d(LOG_TAG, "isMT = " + dc.isMT);
      Log.d(LOG_TAG, "als = " + dc.als);
      Log.d(LOG_TAG, "isVoice = " + dc.isVoice);
      Log.d(LOG_TAG, "isVideo = " + isVideo);
      Log.d(LOG_TAG, "number = " + dc.number);
      Log.d(LOG_TAG, "np = " + np);
      Log.d(LOG_TAG, "name = " + dc.name);
      Log.d(LOG_TAG, "namePresentation = " + dc.namePresentation);
      Log.d(LOG_TAG, "uusInfoPresent = " + uusInfoPresent);

      if (uusInfoPresent == 1) {
        dc.uusInfo = new UUSInfo();
        dc.uusInfo.setType(p.readInt());
        dc.uusInfo.setDcs(p.readInt());
        byte[] userData = p.createByteArray();
        dc.uusInfo.setUserData(userData);
        Log.v(
            LOG_TAG,
            String.format(
                "Incoming UUS : type=%d, dcs=%d, length=%d",
                dc.uusInfo.getType(), dc.uusInfo.getDcs(), dc.uusInfo.getUserData().length));
        Log.v(LOG_TAG, "Incoming UUS : data (string)=" + new String(dc.uusInfo.getUserData()));
        Log.v(
            LOG_TAG,
            "Incoming UUS : data (hex): " + IccUtils.bytesToHexString(dc.uusInfo.getUserData()));
      } else {
        Log.v(LOG_TAG, "Incoming UUS : NOT present!");
      }

      // Make sure there's a leading + on addresses with a TOA of 145
      dc.number = PhoneNumberUtils.stringFromStringAndTOA(dc.number, dc.TOA);

      response.add(dc);

      if (dc.isVoicePrivacy) {
        mVoicePrivacyOnRegistrants.notifyRegistrants();
        Log.d(LOG_TAG, "InCall VoicePrivacy is enabled");
      } else {
        mVoicePrivacyOffRegistrants.notifyRegistrants();
        Log.d(LOG_TAG, "InCall VoicePrivacy is disabled");
      }
    }

    Collections.sort(response);

    return response;
  }

  @Override
  protected Object responseGetPreferredNetworkType(Parcel p) {
    int[] response = (int[]) responseInts(p);

    if (response.length >= 1) {
      // Since this is the response for getPreferredNetworkType
      // we'll assume that it should be the value we want the
      // vendor ril to take if we reestablish a connection to it.
      mPreferredNetworkType = response[0];
    }

    // When the modem responds Phone.NT_MODE_GLOBAL, it means Phone.NT_MODE_WCDMA_PREF
    if (response[0] == Phone.NT_MODE_GLOBAL) {
      Log.d(LOG_TAG, "Overriding network type response from GLOBAL to WCDMA preferred");
      response[0] = Phone.NT_MODE_WCDMA_PREF;
    }

    return response;
  }

  @Override
  protected Object responseSignalStrength(Parcel p) {
    int numInts = 12;
    int response[];
    boolean isGsm = true;

    // Get raw data
    response = new int[numInts];
    for (int i = 0; i < numInts; i++) {
      response[i] = p.readInt();
    }

    /*
    Log.d(LOG_TAG, "gsmSignalStrength=" + response[0]);
    Log.d(LOG_TAG, "gsmBitErrorRate=" + response[1]);
    Log.d(LOG_TAG, "cdmaDbm=" + response[2]);
    Log.d(LOG_TAG, "cdmaEcio=" + response[3]);
    Log.d(LOG_TAG, "evdoDbm=" + response[4]);
    Log.d(LOG_TAG, "evdoEcio=" + response[5]);
    Log.d(LOG_TAG, "evdoSnr=" + response[6]);
    Log.d(LOG_TAG, "lteSignalStrength=" + response[7]);
    Log.d(LOG_TAG, "lteRsrp=" + response[8]);
    Log.d(LOG_TAG, "lteRsrq=" + response[9]);
    Log.d(LOG_TAG, "lteRssnr=" + response[10]);
    Log.d(LOG_TAG, "lteCqi=" + response[11]);
    */

    int mGsmSignalStrength = response[0]; // Valid values are (0-31, 99) as defined in TS 27.007 8.5
    Log.d(LOG_TAG, "responseSignalStrength (raw): gsmSignalStrength=" + mGsmSignalStrength);
    mGsmSignalStrength = mGsmSignalStrength & 0xff; // Get the first 8 bits
    Log.d(LOG_TAG, "responseSignalStrength (corrected): gsmSignalStrength=" + mGsmSignalStrength);

    /* if mGsmSignalStrength isn't a valid value, use mCdmaDbm as fallback */
    if (mGsmSignalStrength < 0 || (mGsmSignalStrength > 31 && response[0] != 99)) {
      int mCdmaDbm = response[2];
      Log.d(LOG_TAG, "responseSignalStrength-fallback (raw): gsmSignalStrength=" + mCdmaDbm);

      if (mCdmaDbm < 0) {
        mGsmSignalStrength = 99;
      } else if (mCdmaDbm > 31 && mCdmaDbm != 99) {
        mGsmSignalStrength = 31;
      } else {
        mGsmSignalStrength = mCdmaDbm;
      }
      Log.d(
          LOG_TAG,
          "responseSignalStrength-fallback (corrected): gsmSignalStrength=" + mGsmSignalStrength);
    }

    SignalStrength signalStrength =
        new SignalStrength(
            mGsmSignalStrength,
            response[1],
            response[2],
            response[3],
            response[4],
            response[5],
            response[6],
            isGsm);

    return signalStrength;
  }

  @Override
  public void getVoiceRadioTechnology(Message result) {
    RILRequest rr = RILRequest.obtain(RIL_REQUEST_VOICE_RADIO_TECH, result);

    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));

    // RIL versions below 7 do not support this request
    if (mRilVersion >= 7) send(rr);
    else Log.d(LOG_TAG, "RIL_REQUEST_VOICE_RADIO_TECH blocked!!!");
  }

  @Override
  public void getCdmaSubscriptionSource(Message response) {
    RILRequest rr =
        RILRequest.obtain(RILConstants.RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE, response);

    if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest));
    Log.d(LOG_TAG, "RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE blocked!!!");
    // send(rr);
  }
}