Example #1
0
  /** Reset the audio mode */
  private synchronized void actualUnsetAudioInCall() {

    if (!prefs.getBoolean("isSavedAudioState", false) || !isSetAudioMode) {
      return;
    }

    Log.d(THIS_FILE, "Unset Audio In call");

    int inCallStream = Compatibility.getInCallStream(userWantBluetooth);
    if (bluetoothWrapper != null) {
      // This fixes the BT activation but... but... seems to introduce a
      // lot of other issues
      // bluetoothWrapper.setBluetoothOn(true);
      Log.d(THIS_FILE, "Unset bt");
      bluetoothWrapper.setBluetoothOn(false);
    }
    audioManager.setMicrophoneMute(false);
    if (doFocusAudio) {
      audioManager.setStreamSolo(inCallStream, false);
      audioFocusWrapper.unFocus();
    }
    restoreAudioState();

    if (wifiLock != null && wifiLock.isHeld()) {
      wifiLock.release();
    }
    if (screenLock != null && screenLock.isHeld()) {
      Log.d(THIS_FILE, "Release screen lock");
      screenLock.release();
    }

    isSetAudioMode = false;
  }
Example #2
0
  /** 解锁WifiLock */
  public void ReleaseWifiLock() {
    if (!mWifiLock.isHeld()) {
      return;
    }

    mWifiLock.acquire();
  }
Example #3
0
 private void takeWifiLock() {
   if (mWifiLock == null) {
     WifiManager manager = (WifiManager) sContext.getSystemService(Context.WIFI_SERVICE);
     mWifiLock = manager.createWifiLock(WAKE_LOCK_TAG);
     mWifiLock.setReferenceCounted(false);
   }
   mWifiLock.acquire();
 }
  @Override
  public void onPause() {
    super.onPause();

    videoView.pause();

    if (wifiLock != null && wifiLock.isHeld()) {
      wifiLock.release();
    }
  }
Example #5
0
  public void lock() {
    try {
      if (!wakeLock.isHeld()) wakeLock.acquire();
      if (!wifiLock.isHeld()) wifiLock.acquire();

      Log.d(DEBUG_TAG, "Lock");
    } catch (final Exception e) {
      Log.e(DEBUG_TAG, "Error getting Lock: " + e.getMessage());
    }
  }
 @Override
 public void onCompletion(final MediaPlayer mp) {
   if (DEBUG) {
     Log.d(TAG, "Video playback completed");
   }
   completed = true;
   if (wifiLock != null && wifiLock.isHeld()) {
     wifiLock.release();
   }
   if (finishOnComplete) {
     getActivity().finish();
   }
 }
  /**
   * Releases resources used by the service for playback. This includes the "foreground service"
   * status and notification, the wake locks and possibly the MediaPlayer.
   *
   * @param releaseMediaPlayer Indicates whether the Media Player should also be released or not
   */
  void relaxResources(boolean releaseMediaPlayer) {
    // stop being a foreground service
    stopForeground(true);

    // stop and release the Media Player, if it's available
    if (releaseMediaPlayer && mPlayer != null) {
      mPlayer.reset();
      mPlayer.release();
      mPlayer = null;
    }

    // we can also release the Wifi lock, if we're holding it
    if (mWifiLock.isHeld()) mWifiLock.release();
  }
  /**
   * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
   * from our Media Retriever (that is, it will be a random song in the user's device). If manualUrl
   * is non-null, then it specifies the URL or path to the song that will be played next.
   */
  void playNextSong(String manualUrl) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
      if (manualUrl != null) {
        // set the source of the media player to a manual URL or path
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(manualUrl);
        mSongTitle = manualUrl;
        mIsStreaming = manualUrl.startsWith("http:") || manualUrl.startsWith("https:");
      } else {
        mIsStreaming = false; // playing a locally available song

        MusicRetriever.Item item = mRetriever.getRandomItem();
        if (item == null) {
          say("No song to play :-(");
          return;
        }

        // set the source of the media player a a content URI
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(getApplicationContext(), item.getURI());
        mSongTitle = item.getTitle();
      }

      mState = State.Preparing;
      setUpAsForeground(mSongTitle + " (loading)");

      // starts preparing the media player in the background. When it's done, it will call
      // our OnPreparedListener (that is, the onPrepared() method on this class, since we set
      // the listener to 'this').
      //
      // Until the media player is prepared, we *cannot* call start() on it!
      mPlayer.prepareAsync();

      // If we are streaming from the internet, we want to hold a Wifi lock, which prevents
      // the Wifi radio from going to sleep while the song is playing. If, on the other hand,
      // we are *not* streaming, we want to release the lock if we were holding it before.
      if (mIsStreaming) mWifiLock.acquire();
      else if (mWifiLock.isHeld()) mWifiLock.release();
    } catch (IOException ex) {
      Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
Example #9
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    if (!WifiFeature.isWifiSupported(getContext())) {
      // skip the test if WiFi is not supported
      return;
    }
    mMySync = new MySync();
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    mIntentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);

    mContext.registerReceiver(mReceiver, mIntentFilter);
    mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
    assertNotNull(mWifiManager);
    mWifiLock = mWifiManager.createWifiLock(TAG);
    mWifiLock.acquire();
    if (!mWifiManager.isWifiEnabled()) setWifiEnabled(true);
    Thread.sleep(ENABLE_WAIT_MSEC);
    assertTrue(mWifiManager.isWifiEnabled());
    mMySync.expectedState = STATE_NULL;
  }
Example #10
0
  public void onCallStateChanged(final LinphoneCall call, final State state, final String message) {
    if (instance == null) {
      Log.i("Service not ready, discarding call state change to ", state.toString());
      return;
    }
    if (state == LinphoneCall.State.IncomingReceived) {
      onIncomingReceived();
    }

    if (state == State.CallUpdatedByRemote) {
      // If the correspondent proposes video while audio call
      boolean remoteVideo = call.getRemoteParams().getVideoEnabled();
      boolean localVideo = call.getCurrentParamsCopy().getVideoEnabled();
      boolean autoAcceptCameraPolicy = LinphoneManager.getInstance().isAutoAcceptCamera();
      if (remoteVideo && !localVideo && !autoAcceptCameraPolicy) {
        try {
          LinphoneManager.getLc().deferCallUpdate(call);

          if (incallListener() != null) incallListener().onCallStateChanged(call, state, message);
        } catch (LinphoneCoreException e) {
          e.printStackTrace();
        }
      }
    }

    if (state == State.StreamsRunning) {
      // Workaround bug current call seems to be updated after state changed to streams running
      //	refreshIncallIcon(call);
      mWifiLock.acquire();
    } else {
      //	refreshIncallIcon(LinphoneManager.getLc().getCurrentCall());
    }
    if ((state == State.CallEnd || state == State.Error)
        && LinphoneManager.getLc().getCallsNb() < 1) {
      mWifiLock.release();
    }
    //		mHandler.post(new Runnable() {
    //			public void run() {
    //				if (guiListener() != null)
    //					guiListener().onCallStateChanged(call, state, message);
    //			}
    //		});
  }
  @Override
  public void onResume() {
    super.onResume();

    if (autoResumeManagement) {
      videoView.start();
    }

    if (wifiLock != null && !completed) {
      wifiLock.acquire();
    }
  }
Example #12
0
  @Override
  public synchronized void onDestroy() {
    instance = null;
    LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Offline);
    LinphoneManager.destroy();

    // Make sure our notification is gone.
    //	    stopForegroundCompat(NOTIF_ID);
    //	    mNM.cancel(INCALL_NOTIF_ID);
    mWifiLock.release();
    super.onDestroy();
  }
Example #13
0
 @Override
 protected void tearDown() throws Exception {
   if (!WifiFeature.isWifiSupported(getContext())) {
     // skip the test if WiFi is not supported
     super.tearDown();
     return;
   }
   mWifiLock.release();
   mContext.unregisterReceiver(mReceiver);
   if (!mWifiManager.isWifiEnabled()) setWifiEnabled(true);
   Thread.sleep(ENABLE_WAIT_MSEC);
   super.tearDown();
 }
Example #14
0
  public static void clean(boolean releaseLocks) {
    setForwarding(false);

    try {
      if (releaseLocks) {
        Logger.debug("Releasing locks.");

        if (mWifiLock != null && mWifiLock.isHeld()) mWifiLock.release();

        if (mWakeLock != null && mWakeLock.isHeld()) mWakeLock.release();
      }

      synchronized (mTargets) {
        for (Target t : mTargets) for (Session s : t.getSessions()) s.stopSession();

        mTargets.clear();
      }

      Client.Disconnect();
      mCoreInitialized = false;
    } catch (Exception e) {
      errorLogging(e);
    }
  }
Example #15
0
  private void prePoll() {
    mWifiLock = null;

    if (!checkConnectivity()) {
      WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
      mWifiLock = wm.createWifiLock(getClass().getSimpleName());

      mWifiLock.acquire();

      long start = System.currentTimeMillis();
      while (!checkConnectivity() && System.currentTimeMillis() - start < Millis.SEC * 10) {
        Sleep.sleep(Millis.SEC);
      }
    }
  }
  private void initView(View view) {
    listView = (ListView) view.findViewById(R.id.myCenter_listView);
    mTvStatusInfo = (TextView) view.findViewById(R.id.wifi_tv_createap_ssid);
    mCheckBox = (CheckBox) view.findViewById(R.id.ck_clouds_dog_switch);

    mWiFiMainView = (WiFiMainView) view.findViewById(R.id.wifi_main_ly);
    mWiFiConnectView = (WiFiConnectView) view.findViewById(R.id.wifi_connect_wlan_ly);
    // mWiFiMainView.setOnItemClickListener(onItemClickListener);
    mWiFiMainView.setOnClickListener(clickListener);

    int itemWidth = ScreenUtils.getRealWidthValue(getActivity(), ALBUM_ITEM_WIDTH);
    int itemHeight = ScreenUtils.getRealHeightValue(getActivity(), ALBUM_ITEM_HEIGHT);
    AbsListView.LayoutParams param = new AbsListView.LayoutParams(itemWidth, itemHeight);
    ReturnBarView.LayoutParams lp = new ReturnBarView.LayoutParams(itemWidth, itemHeight);

    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "lock");
    // 添加wifi锁
    wifiLock.acquire();
    initShowReturnBarView(view);
  }
Example #17
0
  public static void init(Context context) throws Exception {
    mContext = context;
    try {
      Logger.debug("initializing System...");
      mStoragePath =
          getSettings()
              .getString("PREF_SAVE_PATH", Environment.getExternalStorageDirectory().toString());
      mSessionName = "csploit-session-" + java.lang.System.currentTimeMillis();
      mKnownIssues = new KnownIssues();
      mPlugins = new ArrayList<Plugin>();
      mOpenPorts = new SparseIntArray(3);

      // if we are here, network initialization didn't throw any error, lock wifi
      WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);

      if (mWifiLock == null)
        mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "wifiLock");

      if (!mWifiLock.isHeld()) mWifiLock.acquire();

      // wake lock if enabled
      if (getSettings().getBoolean("PREF_WAKE_LOCK", true)) {
        PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);

        if (mWakeLock == null)
          mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wakeLock");

        if (!mWakeLock.isHeld()) mWakeLock.acquire();
      }

      // set ports
      try {
        HTTP_PROXY_PORT = Integer.parseInt(getSettings().getString("PREF_HTTP_PROXY_PORT", "8080"));
        HTTP_SERVER_PORT =
            Integer.parseInt(getSettings().getString("PREF_HTTP_SERVER_PORT", "8081"));
        HTTPS_REDIR_PORT =
            Integer.parseInt(getSettings().getString("PREF_HTTPS_REDIRECTOR_PORT", "8082"));
        MSF_RPC_PORT = Integer.parseInt(getSettings().getString("MSF_RPC_PORT", "55553"));
      } catch (NumberFormatException e) {
        HTTP_PROXY_PORT = 8080;
        HTTP_SERVER_PORT = 8081;
        HTTPS_REDIR_PORT = 8082;
        MSF_RPC_PORT = 55553;
      }

      // initialize network data at the end
      mNetwork = new Network(mContext);

      Target network = new Target(mNetwork),
          gateway = new Target(mNetwork.getGatewayAddress(), mNetwork.getGatewayHardware()),
          device = new Target(mNetwork.getLocalAddress(), mNetwork.getLocalHardware());

      gateway.setAlias(mNetwork.getSSID());
      device.setAlias(android.os.Build.MODEL);

      mTargets.add(network);
      mTargets.add(gateway);
      mTargets.add(device);

      mInitialized = true;
    } catch (Exception e) {
      if (!(e instanceof NoRouteToHostException)) errorLogging(e);

      throw e;
    }
  }
Example #18
0
  @Override
  public void onCreate() {
    super.onCreate();

    android.util.Log.d("LinphoneService", "onCreate()");

    // In case restart after a crash. Main in LinphoneActivity
    LinphonePreferenceManager.getInstance(this);

    // Set default preferences
    PreferenceManager.setDefaultValues(this, R.get("xml", "preferences"), true);

    //		mNotificationTitle = getString(R.get("string", "app_name"));

    // Dump some debugging information to the logs
    Log.i(START_LINPHONE_LOGS);
    dumpDeviceInformation();
    dumpInstalledLinphoneInformation();

    //		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    //		mNM.cancel(INCALL_NOTIF_ID); // in case of crash the icon is not removed
    //		mNotif = new Notification(R.get("drawable", "status_level"), "",
    // System.currentTimeMillis());
    //		mNotif.iconLevel=IC_LEVEL_ORANGE;
    //		mNotif.flags |= Notification.FLAG_ONGOING_EVENT;

    //		Intent notifIntent = new Intent();
    //		notifIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    //		notifIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
    // Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    //		notifIntent.setClassName(ALModuleProxy.PKG_NAME, ALModuleProxy.PKG_NAME + "." +
    // ALModuleProxy.ACT_NAME);
    //		notifIntent.setAction(Intent.ACTION_MAIN);
    //		mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, 0);
    //		mNotif.setLatestEventInfo(this, mNotificationTitle,"", mNotifContentIntent);

    LinphoneManager.createAndStart(this, this);
    LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Online);
    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    mWifiLock =
        mWifiManager.createWifiLock(
            WifiManager.WIFI_MODE_FULL_HIGH_PERF, this.getPackageName() + "-wifi-call-lock");
    mWifiLock.setReferenceCounted(false);
    instance = this; // instance is ready once linphone manager has been created

    // Retrieve methods to publish notification and keep Android
    // from killing us and keep the audio quality high.
    if (Version.sdkStrictlyBelow(Version.API05_ECLAIR_20)) {
      try {
        mSetForeground = getClass().getMethod("setForeground", mSetFgSign);
      } catch (NoSuchMethodException e) {
        Log.e(e, "Couldn't find foreground method");
      }
    } else {
      try {
        mStartForeground = getClass().getMethod("startForeground", mStartFgSign);
        mStopForeground = getClass().getMethod("stopForeground", mStopFgSign);
      } catch (NoSuchMethodException e) {
        Log.e(e, "Couldn't find startGoreground or stopForeground");
      }
    }

    //		startForegroundCompat(NOTIF_ID, mNotif);

    LinphoneManager.setOnTextReceivedListener(this);

    if (!mTestDelayElapsed) {
      // Only used when testing. Simulates a 5 seconds delay for launching service
      mHandler.postDelayed(
          new Runnable() {
            @Override
            public void run() {
              mTestDelayElapsed = true;
            }
          },
          5000);
    }
  }
    @Override
    public void run() {
      _wifiLock.acquire();
      final String asxUrl = _episode.getAsxUrl();
      AsxModel asx;
      try {
        asx = AsxModel.createModelFromUrl(asxUrl);
      } catch (IOException e) {
        e.printStackTrace();
        _handler.sendDownloadFailedMessage();
        return;
      }
      final List<AsxEntryModel> entries = asx.getEntries();
      final String[] playlist = new String[entries.size()];
      for (int i = 0; i < playlist.length; i++) {
        final AsxEntryModel entry = entries.get(i);
        final String ref = entry.getRef();
        playlist[i] = ref;
      }

      long totalSize = 10L;
      for (final String url : playlist) {
        try {
          final MMSInputStream mmsStream = new MMSInputStream(url);
          totalSize += mmsStream.getSize();
          mmsStream.close();
        } catch (final Exception e) {
          Log.e(TAG, e.getMessage());
          _handler.sendDownloadFailedMessage();
          _wifiLock.release();
          return;
        }
      }
      _handler.sendTotalSizeUpdateMessage(totalSize);

      for (final String url : playlist) {
        _threadFinishedCount = 0;
        try {
          final MMSInputStream mmsStream = new MMSInputStream(url);
          final long size = mmsStream.getSize();
          final double length = mmsStream.getLength();

          final List<FileOutputStream> files;
          final String filePath;
          try {
            final String externalStorageState = Environment.getExternalStorageState();
            if (externalStorageState.equals(Environment.MEDIA_REMOVED)) {
              _handler.sendDownloadFailedMessage();
              _wifiLock.release();
              mmsStream.close();
              return;
            }
            final File sdCardRoot = Environment.getExternalStorageDirectory();
            final String sdCardPath = sdCardRoot.getPath();
            final File rthkFolder = new File(sdCardPath + "/RthkArchivePlayer");

            if (!rthkFolder.exists()) {
              rthkFolder.mkdirs();
            }

            final String rthkPath = rthkFolder.getPath();
            final String filename = URLEncoder.encode(url, "utf-8");
            filePath = rthkPath + "/" + filename;

            files = new ArrayList<FileOutputStream>(_threadNum);
            String ext = "";
            for (int i = 0; i < _threadNum; i++, ext = ".part" + i) {
              final FileOutputStream stream = new FileOutputStream(filePath + ext);
              files.add(stream);
            }

          } catch (final Exception e) {
            Log.e(TAG, e.getMessage());
            _handler.sendDownloadFailedMessage();
            _wifiLock.release();
            return;
          }

          int streamNum = 0;
          final long stepSize = size / _threadNum;

          long startPos = -1L;
          long readCap = -1L;
          DownloadThread downloadThread = null;

          for (final FileOutputStream file : files) {
            final MMSInputStream stream;
            if (streamNum == 0) {
              stream = mmsStream;
              startPos = 0L;
            } else {
              stream = new MMSInputStream(url);
              final long pos = stream.seekByte(stepSize * streamNum);
              readCap = pos - startPos;
              downloadThread.setReadCapacity(readCap);
              downloadThread.start();
              startPos = pos;
            }

            downloadThread = new DownloadThread(stream, file, streamNum);

            streamNum++;

            if (streamNum == _threadNum) {
              downloadThread.setReadCapacity(size * 2);
              downloadThread.start();
            }
          }

          synchronized (this) {
            while (_threadFinishedCount < _threadNum) {
              try {
                wait();
              } catch (final InterruptedException e) {
                e.printStackTrace();
              }
            }
          }

          final FileOutputStream baseFile = new FileOutputStream(filePath, true);
          ;
          for (int i = 1; i < _threadNum; i++) {
            final String path = filePath + ".part" + i;
            try {
              final File file = new File(path);
              final FileInputStream inputStream = new FileInputStream(file);
              final byte[] buffer = new byte[1024];
              int read = 0;
              while ((read = inputStream.read(buffer)) > 0) {
                baseFile.write(buffer, 0, read);
              }
              inputStream.close();
              file.delete();
            } catch (final IOException e) {
              Log.e(TAG, e.getMessage());
            }
          }
          baseFile.close();

          final AsfFileDbAdapter dbAdapter = new AsfFileDbAdapter(_context);
          dbAdapter.open();
          dbAdapter.createFile(url, filePath, length, size);
          dbAdapter.close();
        } catch (final IOException e) {
          Log.e(TAG, e.getMessage());
          _handler.sendDownloadFailedMessage();
          _wifiLock.release();
          return;
        }
      }
      _wifiLock.release();
      _handler.sendDownloadSuccessMessage();
    }
Example #20
0
	// 解锁wifiLock
	public void releaseWifiLock() {
		// 判断是否锁定
		if (mWifiLock.isHeld()) {
			mWifiLock.acquire();
		}
	}
Example #21
0
 private void releaseWifiLock() {
   if (mWifiLock != null) {
     mWifiLock.release();
     mWifiLock = null;
   }
 }
Example #22
0
 // ��WifiLock
 public void acquireWifiLock() {
   mWifiLock.acquire();
 }
Example #23
0
 private void postPoll() {
   if (mWifiLock != null) {
     mWifiLock.release();
   }
 }
Example #24
0
  public static void unlock() {
    if (wakeLock != null && wakeLock.isHeld()) wakeLock.release();
    if (wifiLock != null && wifiLock.isHeld()) wifiLock.release();

    Log.d(DEBUG_TAG, "Unlock");
  }
Example #25
0
 // ����WifiLock
 public void releaseWifiLock() {
   // �ж�ʱ����
   if (mWifiLock.isHeld()) {
     mWifiLock.acquire();
   }
 }
Example #26
0
  /** Set the audio mode as in call */
  @SuppressWarnings("deprecation")
  private synchronized void actualSetAudioInCall() {
    // Ensure not already set
    if (isSetAudioMode) {
      return;
    }
    stopRing();
    saveAudioState();

    // Set the rest of the phone in a better state to not interferate with
    // current call
    // Do that only if we were not already in silent mode
    /*
     * Not needed anymore with on flight gsm call capture
     * if(audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
     * audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
     * AudioManager.VIBRATE_SETTING_ON);
     * audioManager.setVibrateSetting(AudioManager
     * .VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
     * audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); }
     */

    // LOCKS

    // Wifi management if necessary
    ContentResolver ctntResolver = service.getContentResolver();
    Settings.System.putInt(
        ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);

    // Acquire wifi lock
    WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE);
    if (wifiLock == null) {
      wifiLock =
          wman.createWifiLock(
              (Compatibility.isCompatible(9))
                  ? WifiManager.WIFI_MODE_FULL_HIGH_PERF
                  : WifiManager.WIFI_MODE_FULL,
              "com.csipsimple.InCallLock");
      wifiLock.setReferenceCounted(false);
    }
    WifiInfo winfo = wman.getConnectionInfo();
    if (winfo != null) {
      DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState());
      // We assume that if obtaining ip addr, we are almost connected so
      // can keep wifi lock
      if (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) {
        if (!wifiLock.isHeld()) {
          wifiLock.acquire();
        }
      }

      // This wake lock purpose is to prevent PSP wifi mode
      if (service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) {
        if (screenLock == null) {
          PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE);
          screenLock =
              pm.newWakeLock(
                  PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
                  "com.csipsimple.onIncomingCall.SCREEN");
          screenLock.setReferenceCounted(false);
        }
        // Ensure single lock
        if (!screenLock.isHeld()) {
          screenLock.acquire();
        }
      }
    }

    if (!useWebRTCImpl) {
      // Audio routing
      int targetMode = getAudioTargetMode();
      Log.d(THIS_FILE, "Set mode audio in call to " + targetMode);

      if (service.getPrefs().generateForSetCall()) {
        boolean needOutOfSilent = (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT);
        if (needOutOfSilent) {
          audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_VOICE_CALL, 1);
        toneGenerator.startTone(41 /* ToneGenerator.TONE_CDMA_CONFIRM */);
        toneGenerator.stopTone();
        toneGenerator.release();
        // Restore silent mode
        if (needOutOfSilent) {
          audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
      }

      // Set mode
      if (targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) {
        // For galaxy S we need to set in call mode before to reset
        // stack
        audioManager.setMode(AudioManager.MODE_IN_CALL);
      }

      audioManager.setMode(targetMode);

      // Routing
      if (service.getPrefs().useRoutingApi()) {
        audioManager.setRouting(
            targetMode,
            userWantSpeaker ? AudioManager.ROUTE_SPEAKER : AudioManager.ROUTE_EARPIECE,
            AudioManager.ROUTE_ALL);
      } else {
        audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false);
      }

      audioManager.setMicrophoneMute(false);
      if (bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) {
        Log.d(THIS_FILE, "Try to enable bluetooth");
        bluetoothWrapper.setBluetoothOn(true);
      }

    } else {
      // WebRTC implementation for routing
      int apiLevel = Compatibility.getApiLevel();

      // SetAudioMode
      // ***IMPORTANT*** When the API level for honeycomb (H) has been
      // decided,
      // the condition should be changed to include API level 8 to H-1.
      if (android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) {
        // Set Samsung specific VoIP mode for 2.2 devices
        int mode = 4;
        audioManager.setMode(mode);
        if (audioManager.getMode() != mode) {
          Log.e(THIS_FILE, "Could not set audio mode for Samsung device");
        }
      }

      // SetPlayoutSpeaker
      if ((3 == apiLevel) || (4 == apiLevel)) {
        // 1.5 and 1.6 devices
        if (userWantSpeaker) {
          // route audio to back speaker
          audioManager.setMode(AudioManager.MODE_NORMAL);
        } else {
          // route audio to earpiece
          audioManager.setMode(AudioManager.MODE_IN_CALL);
        }
      } else {
        // 2.x devices
        if ((android.os.Build.BRAND.equalsIgnoreCase("samsung"))
            && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) {
          // Samsung 2.0, 2.0.1 and 2.1 devices
          if (userWantSpeaker) {
            // route audio to back speaker
            audioManager.setMode(AudioManager.MODE_IN_CALL);
            audioManager.setSpeakerphoneOn(userWantSpeaker);
          } else {
            // route audio to earpiece
            audioManager.setSpeakerphoneOn(userWantSpeaker);
            audioManager.setMode(AudioManager.MODE_NORMAL);
          }
        } else {
          // Non-Samsung and Samsung 2.2 and up devices
          audioManager.setSpeakerphoneOn(userWantSpeaker);
        }
      }
    }

    // Set stream solo/volume/focus

    int inCallStream = Compatibility.getInCallStream(userWantBluetooth);
    if (doFocusAudio) {
      if (!accessibilityManager.isEnabled()) {
        audioManager.setStreamSolo(inCallStream, true);
      }
      audioFocusWrapper.focus(userWantBluetooth);
    }
    Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel());
    setStreamVolume(
        inCallStream,
        (int)
            (audioManager.getStreamMaxVolume(inCallStream)
                * service.getPrefs().getInitialVolumeLevel()),
        0);

    isSetAudioMode = true;
    // System.gc();
  }