Beispiel #1
0
 public void onCreate() {
   super.onCreate();
   Log.m11091e("dddd", "Call SipLibService onCreate");
   Log.m11095i(START_LINPHONE_LOGS);
   this.mNM = (NotificationManager) getSystemService("notification");
   LinphoneManager.createAndStart(this, this);
   this.mWifiManager = (WifiManager) getSystemService("wifi");
   if (Version.sdkAboveOrEqual(12)) {
     startWifiLock();
   }
   instance = this;
   if (Version.sdkStrictlyBelow(5)) {
     try {
       getClass().getMethod("setForeground", mSetFgSign);
     } catch (Throwable e) {
       Log.m11090e(e, "Couldn't find foreground method");
     }
   } else {
     try {
       getClass().getMethod("startForeground", mStartFgSign);
       getClass().getMethod("stopForeground", mStopFgSign);
     } catch (Throwable e2) {
       Log.m11090e(e2, "Couldn't find startGoreground or stopForeground");
     }
   }
   if (!this.mTestDelayElapsed) {
     this.mHandler.postDelayed(new C27971(), 5000);
   }
   this.mKeepAlivePendingIntent =
       PendingIntent.getBroadcast(
           this, IC_LEVEL_ORANGE, new Intent(this, KeepAliveHandler.class), 1073741824);
   ((AlarmManager) getSystemService("alarm"))
       .setRepeating(2, SystemClock.elapsedRealtime() + 1000, 60000, this.mKeepAlivePendingIntent);
 }
  public void setPushNotificationEnabled(boolean enable) {
    getConfig().setBool("app", "push_notification", enable);

    if (enable) {
      // Add push infos to exisiting proxy configs
      String regId = getPushNotificationRegistrationID();
      String appId = getString(R.string.push_sender_id);
      if (regId != null && getLc().getProxyConfigList().length > 0) {
        for (LinphoneProxyConfig lpc : getLc().getProxyConfigList()) {
          String contactInfos = "app-id=" + appId + ";pn-type=google;pn-tok=" + regId;
          lpc.edit();
          lpc.setContactUriParameters(contactInfos);
          lpc.done();
          Log.d("Push notif infos added to proxy config");
        }
        getLc().refreshRegisters();
      }
    } else {
      if (getLc().getProxyConfigList().length > 0) {
        for (LinphoneProxyConfig lpc : getLc().getProxyConfigList()) {
          lpc.edit();
          lpc.setContactUriParameters(null);
          lpc.done();
          Log.d("Push notif infos removed from proxy config");
        }
        getLc().refreshRegisters();
      }
    }
  }
  private boolean importAndroidStoredMessagedIntoLibLinphoneStorage() {
    Log.w("Importing previous messages into new database...");
    try {
      ChatStorage db = LinphoneActivity.instance().getChatStorage();
      List<String> conversations = db.getChatList();
      for (int j = conversations.size() - 1; j >= 0; j--) {
        String correspondent = conversations.get(j);
        LinphoneChatRoom room = LinphoneManager.getLc().getOrCreateChatRoom(correspondent);
        for (ChatMessage message : db.getMessages(correspondent)) {
          LinphoneChatMessage msg =
              room.createLinphoneChatMessage(
                  message.getMessage(),
                  message.getUrl(),
                  message.getStatus(),
                  Long.parseLong(message.getTimestamp()),
                  true,
                  message.isIncoming());
          if (message.getImage() != null) {
            String path = saveImageAsFile(message.getId(), message.getImage());
            if (path != null) msg.setExternalBodyUrl(path);
          }
          msg.store();
        }
        db.removeDiscussion(correspondent);
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
    @Override
    public void onOrientationChanged(final int o) {
      if (o == OrientationEventListener.ORIENTATION_UNKNOWN) {
        return;
      }

      int degrees = 270;
      if (o < 45 || o > 315) degrees = 0;
      else if (o < 135) degrees = 90;
      else if (o < 225) degrees = 180;

      if (mAlwaysChangingPhoneAngle == degrees) {
        return;
      }
      mAlwaysChangingPhoneAngle = degrees;

      Log.d("Phone orientation changed to ", degrees);
      int rotation = (360 - degrees) % 360;
      LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
      if (lc != null) {
        lc.setDeviceRotation(rotation);
        LinphoneCall currentCall = lc.getCurrentCall();
        if (currentCall != null
            && currentCall.cameraEnabled()
            && currentCall.getCurrentParamsCopy().getVideoEnabled()) {
          lc.updateCall(currentCall, null);
        }
      }
    }
  private void sendTextMessage(String messageToSend) {
    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    boolean isNetworkReachable = lc == null ? false : lc.isNetworkReachable();

    if (chatRoom != null
        && messageToSend != null
        && messageToSend.length() > 0
        && isNetworkReachable) {
      LinphoneChatMessage chatMessage = chatRoom.createLinphoneChatMessage(messageToSend);
      chatRoom.sendMessage(chatMessage, this);

      if (LinphoneActivity.isInstanciated()) {
        LinphoneActivity.instance().onMessageSent(sipUri, messageToSend);
      }

      adapter.refreshHistory();
      adapter.notifyDataSetChanged();

      Log.i("Sent message current status: " + chatMessage.getStatus());
      scrollToEnd();
    } else if (!isNetworkReachable && LinphoneActivity.isInstanciated()) {
      LinphoneActivity.instance()
          .displayCustomToast(getString(R.string.error_network_unreachable), Toast.LENGTH_LONG);
    }
  }
 public void disableProvisioningLoginView() {
   if (isProvisioningLoginViewEnabled()) { // Only do it if it was previously enabled
     getConfig().setBool("app", "show_login_view", false);
   } else {
     Log.w("Remote provisioning login view wasn't enabled, ignoring");
   }
 }
Beispiel #7
0
 private synchronized void notifyWrapper(int i, Notification notification) {
   if (instance == null || notification == null) {
     Log.m11095i("Service not ready, discarding notification");
   } else {
     this.mNM.notify(i, notification);
   }
 }
Beispiel #8
0
 @Override
 protected void onUnregistered(Context context, String regId) {
   Log.w("Unregistered push notification : " + regId);
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
   SharedPreferences.Editor editor = prefs.edit();
   editor.putString(context.getString(R.string.push_reg_id_key), null);
   editor.commit();
 }
Beispiel #9
0
 @Override
 protected void onMessage(Context context, Intent intent) {
   Log.d("Push notification received");
   if (LinphoneManager.isInstanciated()) {
     LinphoneManager.getLc().setNetworkReachable(false);
     LinphoneManager.getLc().setNetworkReachable(true);
   }
 }
 private void toggleSpeaker() {
   isSpeakerEnabled = !isSpeakerEnabled;
   if (isSpeakerEnabled) {
     LinphoneManager.getInstance().routeAudioToSpeaker();
     speaker.setBackgroundResource(R.drawable.speaker_on);
     LinphoneManager.getLc().enableSpeaker(isSpeakerEnabled);
   } else {
     Log.d("Toggle speaker off, routing back to earpiece");
     LinphoneManager.getInstance().routeAudioToReceiver();
     speaker.setBackgroundResource(R.drawable.speaker_off);
   }
 }
  private void displayCall(Resources resources, LinphoneCall call, int index) {
    String sipUri = call.getRemoteAddress().asStringUriOnly();
    LinphoneAddress lAddress;
    try {
      lAddress = LinphoneCoreFactory.instance().createLinphoneAddress(sipUri);
    } catch (LinphoneCoreException e) {
      Log.e("Incall activity cannot parse remote address", e);
      lAddress =
          LinphoneCoreFactory.instance().createLinphoneAddress("uknown", "unknown", "unkonown");
    }

    // Control Row
    LinearLayout callView =
        (LinearLayout) inflater.inflate(R.layout.active_call_control_row, container, false);
    callView.setId(index + 1);
    setContactName(callView, lAddress, sipUri, resources);
    displayCallStatusIconAndReturnCallPaused(callView, call);
    setRowBackground(callView, index);
    registerCallDurationTimer(callView, call);
    callsList.addView(callView);

    // Image Row
    LinearLayout imageView =
        (LinearLayout) inflater.inflate(R.layout.active_call_image_row, container, false);
    Contact contact =
        ContactsManager.getInstance()
            .findContactWithAddress(imageView.getContext().getContentResolver(), lAddress);
    if (contact != null) {
      displayOrHideContactPicture(
          imageView, contact.getPhotoUri(), contact.getThumbnailUri(), false);
    } else {
      displayOrHideContactPicture(imageView, null, null, false);
    }
    callsList.addView(imageView);

    callView.setTag(imageView);
    callView.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            if (v.getTag() != null) {
              View imageView = (View) v.getTag();
              if (imageView.getVisibility() == View.VISIBLE) imageView.setVisibility(View.GONE);
              else imageView.setVisibility(View.VISIBLE);
              callsList.invalidate();
            }
          }
        });
  }
  public void displayHistoryDetail(String sipUri, LinphoneCallLog log) {
    LinphoneAddress lAddress;
    try {
      lAddress = LinphoneCoreFactory.instance().createLinphoneAddress(sipUri);
    } catch (LinphoneCoreException e) {
      Log.e("Cannot display history details", e);
      return;
    }
    Contact c =
        ContactsManager.getInstance().findContactWithAddress(getContentResolver(), lAddress);

    String displayName = c != null ? c.getName() : null;
    String pictureUri = c != null && c.getPhotoUri() != null ? c.getPhotoUri().toString() : null;

    String status;
    if (log.getDirection() == CallDirection.Outgoing) {
      status = "Outgoing";
    } else {
      if (log.getStatus() == CallStatus.Missed) {
        status = "Missed";
      } else {
        status = "Incoming";
      }
    }

    String callTime = secondsToDisplayableString(log.getCallDuration());
    String callDate = String.valueOf(log.getTimestamp());

    Fragment fragment2 = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer2);
    if (fragment2 != null
        && fragment2.isVisible()
        && currentFragment == FragmentsAvailable.HISTORY_DETAIL) {
      HistoryDetailFragment historyDetailFragment = (HistoryDetailFragment) fragment2;
      historyDetailFragment.changeDisplayedHistory(
          sipUri, displayName, pictureUri, status, callTime, callDate);
    } else {
      Bundle extras = new Bundle();
      extras.putString("SipUri", sipUri);
      if (displayName != null) {
        extras.putString("DisplayName", displayName);
        extras.putString("PictureUri", pictureUri);
      }
      extras.putString("CallStatus", status);
      extras.putString("CallTime", callTime);
      extras.putString("CallDate", callDate);

      changeCurrentFragment(FragmentsAvailable.HISTORY_DETAIL, extras);
    }
  }
  public LpConfig getConfig() {
    LinphoneCore lc = getLc();
    if (lc != null) {
      return lc.getConfig();
    }

    if (!LinphoneManager.isInstanciated()) {
      Log.w("LinphoneManager not instanciated yet...");
      return LinphoneCoreFactory.instance()
          .createLpConfig(mContext.getFilesDir().getAbsolutePath() + "/.linphonerc");
    }

    return LinphoneCoreFactory.instance()
        .createLpConfig(LinphoneManager.getInstance().mLinphoneConfigFile);
  }
Beispiel #14
0
  @Override
  protected void onRegistered(Context context, String regId) {
    Log.d("Registered push notification : " + regId);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(context.getString(R.string.push_reg_id_key), regId);
    editor.commit();

    if (LinphoneManager.isInstanciated()) {
      try {
        LinphoneManager.getInstance().initAccounts();
      } catch (LinphoneCoreException e) {
        e.printStackTrace();
      }
    }
  }
  public void sendLogs(Context context, String info) {
    final String appName = context.getString(R.string.app_name);

    Intent i = new Intent(Intent.ACTION_SEND);
    i.putExtra(
        Intent.EXTRA_EMAIL, new String[] {context.getString(R.string.about_bugreport_email)});
    i.putExtra(Intent.EXTRA_SUBJECT, appName + " Logs");
    i.putExtra(Intent.EXTRA_TEXT, info);
    i.setType("application/zip");

    try {
      startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
      Log.e(ex);
    }
  }
  public void switchCamera() {
    try {
      int videoDeviceId = LinphoneManager.getLc().getVideoDevice();
      videoDeviceId = (videoDeviceId + 1) % AndroidCameraConfiguration.retrieveCameras().length;
      LinphoneManager.getLc().setVideoDevice(videoDeviceId);
      CallManager.getInstance().updateCall();

      // previous call will cause graph reconstruction -> regive preview
      // window
      if (mCaptureView != null) {
        LinphoneManager.getLc().setPreviewWindow(mCaptureView);
      }
    } catch (ArithmeticException ae) {
      Log.e("Cannot swtich camera : no camera");
    }
  }
 public void setUpnpEnabled(boolean enabled) {
   if (enabled) {
     if (isIceEnabled()) {
       Log.e("Cannot have both ice and upnp enabled, disabling upnp");
     } else {
       getLc().setFirewallPolicy(FirewallPolicy.UseUpnp);
     }
   } else {
     String stun = getStunServer();
     if (stun != null && stun.length() > 0) {
       getLc().setFirewallPolicy(FirewallPolicy.UseStun);
     } else {
       getLc().setFirewallPolicy(FirewallPolicy.NoFirewall);
     }
   }
 }
Beispiel #18
0
  @Override
  public void onLinphoneChatMessageFileTransferReceived(
      LinphoneChatMessage msg, LinphoneContent content, LinphoneBuffer buffer) {
    if (mDownloadedImageStream == null) {
      mDownloadedImageStream = new ByteArrayOutputStream();
      mDownloadedImageStreamSize = 0;
    }

    if (buffer != null && buffer.getSize() > 0) {
      try {
        mDownloadedImageStream.write(buffer.getContent());
        mDownloadedImageStreamSize += buffer.getSize();
      } catch (IOException e) {
        Log.e(e);
      }
    }
  }
Beispiel #19
0
  private void sendImageMessage(String path) {
    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    boolean isNetworkReachable = lc == null ? false : lc.isNetworkReachable();

    if (chatRoom != null && path != null && path.length() > 0 && isNetworkReachable) {
      Bitmap bm = BitmapFactory.decodeFile(path);
      if (bm != null) {
        FileUploadPrepareTask task = new FileUploadPrepareTask(getActivity(), path);
        task.execute(bm);
      } else {
        Log.e("Error, bitmap factory can't read " + path);
      }
    } else if (!isNetworkReachable && LinphoneActivity.isInstanciated()) {
      LinphoneActivity.instance()
          .displayCustomToast(getString(R.string.error_network_unreachable), Toast.LENGTH_LONG);
    }
  }
  private void refreshInCallActions() {
    try {
      if (isSpeakerEnabled) {
        speaker.setBackgroundResource(R.drawable.speaker_on);
        routeSpeaker.setBackgroundResource(R.drawable.route_speaker_on);
        routeReceiver.setBackgroundResource(R.drawable.route_receiver_off);
        routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_off);
      } else {
        speaker.setBackgroundResource(R.drawable.speaker_off);
        routeSpeaker.setBackgroundResource(R.drawable.route_speaker_off);
        if (BluetoothManager.getInstance().isUsingBluetoothAudioRoute()) {
          routeReceiver.setBackgroundResource(R.drawable.route_receiver_off);
          routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_on);
        } else {
          routeReceiver.setBackgroundResource(R.drawable.route_receiver_on);
          routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_off);
        }
      }
    } catch (NullPointerException npe) {
      Log.e("Bluetooth: Audio routes menu disabled on tablets for now (4)");
    }

    if (isMicMuted) {
      micro.setBackgroundResource(R.drawable.micro_off);
    } else {
      micro.setBackgroundResource(R.drawable.micro_on);
    }

    if (LinphoneManager.getLc().getCallsNb() > 1) {
      conference.setVisibility(View.VISIBLE);
      pause.setVisibility(View.GONE);
    } else {
      conference.setVisibility(View.GONE);
      pause.setVisibility(View.VISIBLE);

      List<LinphoneCall> pausedCalls =
          LinphoneUtils.getCallsInState(LinphoneManager.getLc(), Arrays.asList(State.Paused));
      if (pausedCalls.size() == 1) {
        pause.setBackgroundResource(R.drawable.pause_on);
      } else {
        pause.setBackgroundResource(R.drawable.pause_off);
      }
    }
  }
Beispiel #21
0
    @Override
    protected byte[] doInBackground(Bitmap... params) {
      Bitmap bm = params[0];

      if (bm.getWidth() >= bm.getHeight() && bm.getWidth() > SIZE_MAX) {
        bm =
            Bitmap.createScaledBitmap(
                bm, SIZE_MAX, (SIZE_MAX * bm.getHeight()) / bm.getWidth(), false);
      } else if (bm.getHeight() >= bm.getWidth() && bm.getHeight() > SIZE_MAX) {
        bm =
            Bitmap.createScaledBitmap(
                bm, (SIZE_MAX * bm.getWidth()) / bm.getHeight(), SIZE_MAX, false);
      }

      // Rotate the bitmap if possible/needed, using EXIF data
      Log.w(path);
      try {
        if (path != null) {
          ExifInterface exif = new ExifInterface(path);
          int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
          Matrix matrix = new Matrix();
          if (pictureOrientation == 6) {
            matrix.postRotate(90);
          } else if (pictureOrientation == 3) {
            matrix.postRotate(180);
          } else if (pictureOrientation == 8) {
            matrix.postRotate(270);
          }
          bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
      byte[] byteArray = stream.toByteArray();
      return byteArray;
    }
  public boolean onScale(CompatibilityScaleGestureDetector detector) {

    Log.i("================videoSize===001==");

    mZoomFactor *= detector.getScaleFactor();
    // Don't let the object get too small or too large.
    // Zoom to make the video fill the screen vertically
    float portraitZoomFactor =
        ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4);
    // Zoom to make the video fill the screen horizontally
    float landscapeZoomFactor =
        ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4);
    mZoomFactor =
        Math.max(0.1f, Math.min(mZoomFactor, Math.max(portraitZoomFactor, landscapeZoomFactor)));

    LinphoneCall currentCall = LinphoneManager.getLc().getCurrentCall();
    if (currentCall != null) {
      currentCall.zoomVideo(mZoomFactor, mZoomCenterX, mZoomCenterY);
      return true;
    }
    return false;
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getArguments() != null && getArguments().getSerializable("About") != null) {
      about = (FragmentsAvailable) getArguments().getSerializable("About");
    }

    View view = inflater.inflate(R.layout.about, container, false);

    TextView aboutText = (TextView) view.findViewById(R.id.AboutText);
    try {
      aboutText.setText(
          String.format(
              getString(R.string.about_text),
              getActivity()
                  .getPackageManager()
                  .getPackageInfo(getActivity().getPackageName(), 0)
                  .versionName));
    } catch (NameNotFoundException e) {
      Log.e(e, "cannot get version name");
    }

    sendLogButton = view.findViewById(R.id.send_log);
    sendLogButton.setOnClickListener(this);
    sendLogButton.setVisibility(
        LinphonePreferences.instance().isDebugEnabled() ? View.VISIBLE : View.GONE);

    resetLogButton = view.findViewById(R.id.reset_log);
    resetLogButton.setOnClickListener(this);
    resetLogButton.setVisibility(
        LinphonePreferences.instance().isDebugEnabled() ? View.VISIBLE : View.GONE);

    exitButton = view.findViewById(R.id.exit);
    exitButton.setOnClickListener(this);
    exitButton.setVisibility(View.VISIBLE);

    return view;
  }
Beispiel #24
0
 public void onCallStateChanged(LinphoneCall linphoneCall, State state, String str) {
   if (instance == null) {
     Log.m11095i("Service not ready, discarding call state change to ", state.toString());
     return;
   }
   if (state == State.IncomingReceived) {
     onIncomingReceived();
   }
   if (state == State.CallUpdatedByRemote) {
     boolean videoEnabled = linphoneCall.getRemoteParams().getVideoEnabled();
     boolean videoEnabled2 = linphoneCall.getCurrentParamsCopy().getVideoEnabled();
     boolean shouldAutomaticallyAcceptVideoRequests =
         LinphonePreferences.instance().shouldAutomaticallyAcceptVideoRequests();
     if (!(!videoEnabled
         || videoEnabled2
         || shouldAutomaticallyAcceptVideoRequests
         || LinphoneManager.getLc().isInConference())) {
       try {
         LinphoneManager.getLc().deferCallUpdate(linphoneCall);
       } catch (Throwable e) {
         C1104b.m6368b((Object) this, e);
       }
     }
   }
   if (state == State.StreamsRunning) {
     if (getResources().getBoolean(C1134b.enable_call_notification)) {}
     if (Version.sdkAboveOrEqual(12)) {
       this.mWifiLock.acquire();
     }
   } else if (getResources().getBoolean(C1134b.enable_call_notification)) {
   }
   if ((state == State.CallEnd || state == State.Error)
       && LinphoneManager.getLc().getCallsNb() < 1
       && Version.sdkAboveOrEqual(12)) {
     this.mWifiLock.release();
   }
   this.mHandler.post(new C28015(linphoneCall, state, str));
 }
Beispiel #25
0
 @Override
 public void onLinphoneChatMessageFileTransferSent(
     LinphoneChatMessage msg,
     LinphoneContent content,
     int offset,
     int size,
     LinphoneBuffer bufferToFill) {
   if (mUploadingImageStream != null && size > 0) {
     byte[] data = new byte[size];
     int read = mUploadingImageStream.read(data, 0, size);
     if (read > 0) {
       bufferToFill.setContent(data);
       bufferToFill.setSize(read);
     } else {
       Log.e(
           "Error, upload task asking for more bytes("
               + size
               + ") than available ("
               + mUploadingImageStream.available()
               + ")");
     }
   }
 }
Beispiel #26
0
  private void sendTextMessage(String messageToSend) {
    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    boolean isNetworkReachable = lc == null ? false : lc.isNetworkReachable();

    if (chatRoom != null
        && messageToSend != null
        && messageToSend.length() > 0
        && isNetworkReachable) {
      LinphoneChatMessage message = chatRoom.createLinphoneChatMessage(messageToSend);
      message.setListener(this);
      chatRoom.sendChatMessage(message);

      if (LinphoneActivity.isInstanciated()) {
        LinphoneActivity.instance().onMessageSent(sipUri, messageToSend);
      }

      invalidate();
      Log.i("Sent message current status: " + message.getStatus());
    } else if (!isNetworkReachable && LinphoneActivity.isInstanciated()) {
      LinphoneActivity.instance()
          .displayCustomToast(getString(R.string.error_network_unreachable), Toast.LENGTH_LONG);
    }
  }
  @Override
  public boolean onDoubleTap(MotionEvent e) {
    if (LinphoneUtils.isCallEstablished(LinphoneManager.getLc().getCurrentCall())) {
      Log.i("================videoSize===002==");
      if (mZoomFactor == 1.f) {
        // Zoom to make the video fill the screen vertically
        float portraitZoomFactor =
            ((float) mVideoView.getHeight()) / (float) ((3 * mVideoView.getWidth()) / 4);
        // Zoom to make the video fill the screen horizontally
        float landscapeZoomFactor =
            ((float) mVideoView.getWidth()) / (float) ((3 * mVideoView.getHeight()) / 4);

        mZoomFactor = Math.max(portraitZoomFactor, landscapeZoomFactor);
      } else {
        resetZoom();
      }

      LinphoneManager.getLc().getCurrentCall().zoomVideo(mZoomFactor, mZoomCenterX, mZoomCenterY);
      return true;
    }

    return false;
  }
  // Added by me
  public void createGroupChat(String groupName, String[] groupMembers, int groupSize) {
    // Intent intent = new Intent(this, ChatActivity.class);
    // intent.putExtra("GroupName", groupName);
    // intent.putExtra("GroupMembers", groupMembers);
    // intent.putExtra("GroupSize", groupSize);
    // intent.putExtra("ChatType", 1);

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    if (lc != null) {
      LinphoneChatRoom chatRoom = null;
      chatRoom = lc.getOrCreateGroupChatRoom(groupName, groupMembers, groupSize, 0, 0);

      if (chatRoom != null) {
        LinphoneAddress la = chatRoom.getPeerAddress();

        String sipUri = la.asStringUriOnly();
        String displayName = la.getDisplayName();
        String addrStr = la.asString();

        // intent.putExtra("SipUri", sipUri);
        // intent.putExtra("DisplayName", displayName);

        LinphoneProxyConfig pc = lc.getDefaultProxyConfig();
        String identity = pc.getIdentity();

        String id = "";
        try {
          la = LinphoneCoreFactory.instance().createLinphoneAddress(identity);
          id = la.getUserName();
        } catch (LinphoneCoreException e) {
          Log.e("Cannot display chat", e);
          // return;
        }

        String message = id + " created group " + groupName;
        LinphoneChatMessage msg = chatRoom.createLinphoneGroupChatMessage(message);
        chatRoom.sendGroupChatMessage(msg);
        // chatRoom.sendGroupMessage(message);

        onMessageSent(sipUri, message);

        goToChatList();

        /*String toDisplay = "Display Name: " + displayName;
        toDisplay += "\nSIP URI: " + sipUri;
        toDisplay += "\nGroup Name: " + chatRoom.getGroupName();
        toDisplay += "\nGroup Address: " + addrStr;
        displayCustomToast(toDisplay, Toast.LENGTH_SHORT);*/
      }

      // LinphoneProxyConfig pc = lc.getDefaultProxyConfig();
      // String identity = pc.getIdentity();
      // displayCustomToast("I am: " + identity, Toast.LENGTH_SHORT);
    }

    /*startOrientationSensor();
    startActivityForResult(intent, CHAT_ACTIVITY);

    LinphoneService.instance().resetMessageNotifCount();
    LinphoneService.instance().removeMessageNotification();
    displayMissedChats(getChatStorage().getUnreadMessageCount());*/
  }
  public void displayChat(String sipUri) {
    if (getResources().getBoolean(R.bool.disable_chat)) {
      return;
    }

    LinphoneAddress lAddress;
    try {
      lAddress = LinphoneCoreFactory.instance().createLinphoneAddress(sipUri);
    } catch (LinphoneCoreException e) {
      Log.e("Cannot display chat", e);
      return;
    }
    Contact contact =
        ContactsManager.getInstance().findContactWithAddress(getContentResolver(), lAddress);
    String displayName = contact != null ? contact.getName() : null;

    String pictureUri = null;
    String thumbnailUri = null;
    if (contact != null && contact.getPhotoUri() != null) {
      pictureUri = contact.getPhotoUri().toString();
      thumbnailUri = contact.getThumbnailUri().toString();
    }

    if (isTablet()) {
      if (currentFragment == FragmentsAvailable.CHATLIST
          || currentFragment == FragmentsAvailable.CHAT) {
        Fragment fragment2 = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer2);
        if (fragment2 != null
            && fragment2.isVisible()
            && currentFragment == FragmentsAvailable.CHAT) {
          ChatFragment chatFragment = (ChatFragment) fragment2;
          chatFragment.changeDisplayedChat(sipUri, displayName, pictureUri);
        } else {
          Bundle extras = new Bundle();
          extras.putString("SipUri", sipUri);
          if (contact != null) {
            extras.putString("DisplayName", displayName);
            extras.putString("PictureUri", pictureUri);
            extras.putString("ThumbnailUri", thumbnailUri);
          }
          changeCurrentFragment(FragmentsAvailable.CHAT, extras);
        }
      } else {
        changeCurrentFragment(FragmentsAvailable.CHATLIST, null);
        displayChat(sipUri);
      }
      if (messageListFragment != null && messageListFragment.isVisible()) {
        ((ChatListFragment) messageListFragment).refresh();
      }
    } else {
      Intent intent = new Intent(this, ChatActivity.class);
      intent.putExtra("SipUri", sipUri);
      if (contact != null) {
        intent.putExtra("DisplayName", contact.getName());
        intent.putExtra("PictureUri", pictureUri);
        intent.putExtra("ThumbnailUri", thumbnailUri);
      }
      startOrientationSensor();
      startActivityForResult(intent, CHAT_ACTIVITY);
    }

    LinphoneService.instance().resetMessageNotifCount();
    LinphoneService.instance().removeMessageNotification();
    displayMissedChats(getChatStorage().getUnreadMessageCount());
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (isTablet() && getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    } else if (!isTablet()
        && getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    if (!LinphoneManager.isInstanciated()) {
      Log.e("No service running: avoid crash by starting the launcher", this.getClass().getName());
      // super.onCreate called earlier
      finish();
      startActivity(getIntent().setClass(this, LinphoneLauncherActivity.class));
      return;
    }

    boolean useFirstLoginActivity =
        getResources().getBoolean(R.bool.display_account_wizard_at_first_start);
    if (LinphonePreferences.instance().isProvisioningLoginViewEnabled()) {
      Intent wizard = new Intent();
      wizard.setClass(this, RemoteProvisioningLoginActivity.class);
      wizard.putExtra("Domain", LinphoneManager.getInstance().wizardLoginViewDomain);
      startActivityForResult(wizard, REMOTE_PROVISIONING_LOGIN_ACTIVITY);
    } else if (useFirstLoginActivity && LinphonePreferences.instance().isFirstLaunch()) {
      if (LinphonePreferences.instance().getAccountCount() > 0) {
        LinphonePreferences.instance().firstLaunchSuccessful();
      } else {
        startActivityForResult(
            new Intent().setClass(this, SetupActivity.class), FIRST_LOGIN_ACTIVITY);
      }
    }

    if (getResources().getBoolean(R.bool.use_linphone_tag)) {
      ContactsManager.getInstance()
          .initializeSyncAccount(getApplicationContext(), getContentResolver());
    } else {
      ContactsManager.getInstance()
          .initializeContactManager(getApplicationContext(), getContentResolver());
    }

    if (!LinphonePreferences.instance().isContactsMigrationDone()) {
      ContactsManager.getInstance().migrateContacts();
      LinphonePreferences.instance().contactsMigrationDone();
    }

    setContentView(R.layout.main);
    instance = this;
    fragmentsHistory = new ArrayList<FragmentsAvailable>();
    initButtons();

    currentFragment = nextFragment = FragmentsAvailable.DIALER;
    fragmentsHistory.add(currentFragment);
    if (savedInstanceState == null) {
      if (findViewById(R.id.fragmentContainer) != null) {
        dialerFragment = new DialerFragment();
        dialerFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragmentContainer, dialerFragment, currentFragment.toString())
            .commit();
        selectMenu(FragmentsAvailable.DIALER);
      }
    }

    mListener =
        new LinphoneCoreListenerBase() {
          @Override
          public void messageReceived(
              LinphoneCore lc, LinphoneChatRoom cr, LinphoneChatMessage message) {
            if (!displayChatMessageNotification(message.getFrom().asStringUriOnly())) {
              cr.markAsRead();
            }
            displayMissedChats(getChatStorage().getUnreadMessageCount());
            if (messageListFragment != null && messageListFragment.isVisible()) {
              ((ChatListFragment) messageListFragment).refresh();
            }
          }

          @Override
          public void registrationState(
              LinphoneCore lc,
              LinphoneProxyConfig proxy,
              LinphoneCore.RegistrationState state,
              String smessage) {
            if (state.equals(RegistrationState.RegistrationCleared)) {
              if (lc != null) {
                LinphoneAuthInfo authInfo =
                    lc.findAuthInfo(proxy.getIdentity(), proxy.getRealm(), proxy.getDomain());
                if (authInfo != null) lc.removeAuthInfo(authInfo);
              }
            }
          }

          @Override
          public void callState(
              LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
            if (state == State.IncomingReceived) {
              startActivity(new Intent(LinphoneActivity.instance(), IncomingCallActivity.class));
            } else if (state == State.OutgoingInit) {
              if (call.getCurrentParamsCopy().getVideoEnabled()) {
                startVideoActivity(call);
              } else {
                startIncallActivity(call);
              }
            } else if (state == State.CallEnd
                || state == State.Error
                || state == State.CallReleased) {
              // Convert LinphoneCore message for internalization
              if (message != null && message.equals("Call declined.")) {
                displayCustomToast(getString(R.string.error_call_declined), Toast.LENGTH_LONG);
              } else if (message != null && message.equals("Not Found")) {
                displayCustomToast(getString(R.string.error_user_not_found), Toast.LENGTH_LONG);
              } else if (message != null && message.equals("Unsupported media type")) {
                displayCustomToast(getString(R.string.error_incompatible_media), Toast.LENGTH_LONG);
              } else if (message != null && state == State.Error) {
                displayCustomToast(
                    getString(R.string.error_unknown) + " - " + message, Toast.LENGTH_LONG);
              }
              resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
            }

            int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
            displayMissedCalls(missedCalls);
          }
        };

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    if (lc != null) {
      lc.addListener(mListener);
    }

    int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
    displayMissedCalls(missedCalls);

    int rotation = getWindowManager().getDefaultDisplay().getRotation();
    switch (rotation) {
      case Surface.ROTATION_0:
        rotation = 0;
        break;
      case Surface.ROTATION_90:
        rotation = 90;
        break;
      case Surface.ROTATION_180:
        rotation = 180;
        break;
      case Surface.ROTATION_270:
        rotation = 270;
        break;
    }

    LinphoneManager.getLc().setDeviceRotation(rotation);
    mAlwaysChangingPhoneAngle = rotation;

    updateAnimationsState();
  }