public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_BACK) {
     if (currentFragment == FragmentsAvailable.DIALER
         || currentFragment == FragmentsAvailable.CONTACTS
         || currentFragment == FragmentsAvailable.HISTORY
         || currentFragment == FragmentsAvailable.CHATLIST
         || currentFragment == FragmentsAvailable.ABOUT_INSTEAD_OF_CHAT
         || currentFragment == FragmentsAvailable.ABOUT_INSTEAD_OF_SETTINGS) {
       boolean isBackgroundModeActive = LinphonePreferences.instance().isBackgroundModeEnabled();
       if (!isBackgroundModeActive) {
         stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
         finish();
       } else if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) {
         return true;
       }
     } else {
       if (isTablet()) {
         if (currentFragment == FragmentsAvailable.SETTINGS) {
           updateAnimationsState();
         }
       }
     }
   } else if (keyCode == KeyEvent.KEYCODE_MENU && statusFragment != null) {
     if (event.getRepeatCount() < 1) {
       statusFragment.openOrCloseStatusBar(true);
     }
   }
   return super.onKeyDown(keyCode, event);
 }
 public void applyConfigChangesIfNeeded() {
   if (nextFragment != FragmentsAvailable.SETTINGS
       && nextFragment != FragmentsAvailable.ACCOUNT_SETTINGS) {
     updateAnimationsState();
   }
 }
  @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();
  }