RtpSessionActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.Manifest;
   4import android.annotation.SuppressLint;
   5import android.app.PictureInPictureParams;
   6import android.content.ActivityNotFoundException;
   7import android.content.Context;
   8import android.content.Intent;
   9import android.content.pm.PackageManager;
  10import android.os.Build;
  11import android.os.Bundle;
  12import android.os.Handler;
  13import android.os.PowerManager;
  14import android.os.SystemClock;
  15import android.util.Log;
  16import android.util.Rational;
  17import android.view.KeyEvent;
  18import android.view.Menu;
  19import android.view.MenuItem;
  20import android.view.View;
  21import android.view.WindowManager;
  22import android.widget.Toast;
  23
  24import androidx.annotation.NonNull;
  25import androidx.annotation.RequiresApi;
  26import androidx.annotation.StringRes;
  27import androidx.databinding.DataBindingUtil;
  28
  29import com.google.common.base.Optional;
  30import com.google.common.base.Preconditions;
  31import com.google.common.base.Throwables;
  32import com.google.common.collect.ImmutableList;
  33import com.google.common.collect.ImmutableSet;
  34import com.google.common.util.concurrent.FutureCallback;
  35import com.google.common.util.concurrent.Futures;
  36
  37import org.checkerframework.checker.nullness.compatqual.NullableDecl;
  38import org.webrtc.SurfaceViewRenderer;
  39import org.webrtc.VideoTrack;
  40
  41import java.lang.ref.WeakReference;
  42import java.util.Arrays;
  43import java.util.Collections;
  44import java.util.List;
  45import java.util.Set;
  46
  47import eu.siacs.conversations.Config;
  48import eu.siacs.conversations.R;
  49import eu.siacs.conversations.databinding.ActivityRtpSessionBinding;
  50import eu.siacs.conversations.entities.Account;
  51import eu.siacs.conversations.entities.Contact;
  52import eu.siacs.conversations.entities.Conversation;
  53import eu.siacs.conversations.services.AppRTCAudioManager;
  54import eu.siacs.conversations.services.XmppConnectionService;
  55import eu.siacs.conversations.ui.util.AvatarWorkerTask;
  56import eu.siacs.conversations.ui.util.MainThreadExecutor;
  57import eu.siacs.conversations.utils.PermissionUtils;
  58import eu.siacs.conversations.utils.TimeFrameUtils;
  59import eu.siacs.conversations.xml.Namespace;
  60import eu.siacs.conversations.xmpp.Jid;
  61import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
  62import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
  63import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
  64import eu.siacs.conversations.xmpp.jingle.Media;
  65import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
  66
  67import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
  68import static java.util.Arrays.asList;
  69
  70public class RtpSessionActivity extends XmppActivity implements XmppConnectionService.OnJingleRtpConnectionUpdate {
  71
  72    public static final String EXTRA_WITH = "with";
  73    public static final String EXTRA_SESSION_ID = "session_id";
  74    public static final String EXTRA_LAST_REPORTED_STATE = "last_reported_state";
  75    public static final String EXTRA_LAST_ACTION = "last_action";
  76    public static final String ACTION_ACCEPT_CALL = "action_accept_call";
  77    public static final String ACTION_MAKE_VOICE_CALL = "action_make_voice_call";
  78    public static final String ACTION_MAKE_VIDEO_CALL = "action_make_video_call";
  79
  80    private static final int CALL_DURATION_UPDATE_INTERVAL = 333;
  81
  82    private static final List<RtpEndUserState> END_CARD = Arrays.asList(
  83            RtpEndUserState.APPLICATION_ERROR,
  84            RtpEndUserState.DECLINED_OR_BUSY,
  85            RtpEndUserState.CONNECTIVITY_ERROR,
  86            RtpEndUserState.CONNECTIVITY_LOST_ERROR,
  87            RtpEndUserState.RETRACTED
  88    );
  89    private static final List<RtpEndUserState> STATES_SHOWING_HELP_BUTTON = Arrays.asList(
  90            RtpEndUserState.APPLICATION_ERROR,
  91            RtpEndUserState.CONNECTIVITY_ERROR
  92    );
  93    private static final List<RtpEndUserState> STATES_SHOWING_SWITCH_TO_CHAT = Arrays.asList(
  94            RtpEndUserState.CONNECTING,
  95            RtpEndUserState.CONNECTED
  96    );
  97    private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
  98    private static final int REQUEST_ACCEPT_CALL = 0x1111;
  99    private WeakReference<JingleRtpConnection> rtpConnectionReference;
 100
 101    private ActivityRtpSessionBinding binding;
 102    private PowerManager.WakeLock mProximityWakeLock;
 103
 104    private final Handler mHandler = new Handler();
 105    private final Runnable mTickExecutor = new Runnable() {
 106        @Override
 107        public void run() {
 108            updateCallDuration();
 109            mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
 110        }
 111    };
 112
 113    private static Set<Media> actionToMedia(final String action) {
 114        if (ACTION_MAKE_VIDEO_CALL.equals(action)) {
 115            return ImmutableSet.of(Media.AUDIO, Media.VIDEO);
 116        } else {
 117            return ImmutableSet.of(Media.AUDIO);
 118        }
 119    }
 120
 121    private static void addSink(final VideoTrack videoTrack, final SurfaceViewRenderer surfaceViewRenderer) {
 122        try {
 123            videoTrack.addSink(surfaceViewRenderer);
 124        } catch (final IllegalStateException e) {
 125            Log.e(Config.LOGTAG, "possible race condition on trying to display video track. ignoring", e);
 126        }
 127    }
 128
 129    @Override
 130    public void onCreate(Bundle savedInstanceState) {
 131        super.onCreate(savedInstanceState);
 132        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
 133                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
 134                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
 135                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
 136        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_rtp_session);
 137        setSupportActionBar(binding.toolbar);
 138    }
 139
 140    @Override
 141    public boolean onCreateOptionsMenu(final Menu menu) {
 142        getMenuInflater().inflate(R.menu.activity_rtp_session, menu);
 143        final MenuItem help = menu.findItem(R.id.action_help);
 144        final MenuItem gotoChat = menu.findItem(R.id.action_goto_chat);
 145        help.setVisible(isHelpButtonVisible());
 146        gotoChat.setVisible(isSwitchToConversationVisible());
 147        return super.onCreateOptionsMenu(menu);
 148    }
 149
 150    @Override
 151    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
 152        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
 153            if (xmppConnectionService != null) {
 154                if (xmppConnectionService.getNotificationService().stopSoundAndVibration()) {
 155                    return true;
 156                }
 157            }
 158        }
 159        return super.onKeyDown(keyCode, event);
 160    }
 161
 162    private boolean isHelpButtonVisible() {
 163        try {
 164            return STATES_SHOWING_HELP_BUTTON.contains(requireRtpConnection().getEndUserState());
 165        } catch (IllegalStateException e) {
 166            final Intent intent = getIntent();
 167            final String state = intent != null ? intent.getStringExtra(EXTRA_LAST_REPORTED_STATE) : null;
 168            if (state != null) {
 169                return STATES_SHOWING_HELP_BUTTON.contains(RtpEndUserState.valueOf(state));
 170            } else {
 171                return false;
 172            }
 173        }
 174    }
 175
 176    private boolean isSwitchToConversationVisible() {
 177        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 178        return connection != null && STATES_SHOWING_SWITCH_TO_CHAT.contains(connection.getEndUserState());
 179    }
 180
 181    private void switchToConversation() {
 182        final Contact contact = getWith();
 183        final Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true);
 184        switchToConversation(conversation);
 185    }
 186
 187    public boolean onOptionsItemSelected(final MenuItem item) {
 188        switch (item.getItemId()) {
 189            case R.id.action_help:
 190                launchHelpInBrowser();
 191                break;
 192            case R.id.action_goto_chat:
 193                switchToConversation();
 194                break;
 195        }
 196        return super.onOptionsItemSelected(item);
 197    }
 198
 199    private void launchHelpInBrowser() {
 200        final Intent intent = new Intent(Intent.ACTION_VIEW, Config.HELP);
 201        try {
 202            startActivity(intent);
 203        } catch (final ActivityNotFoundException e) {
 204            Toast.makeText(this, R.string.no_application_found_to_open_link, Toast.LENGTH_LONG).show();
 205        }
 206    }
 207
 208    private void endCall(View view) {
 209        endCall();
 210    }
 211
 212    private void endCall() {
 213        if (this.rtpConnectionReference == null) {
 214            retractSessionProposal();
 215            finish();
 216        } else {
 217            requireRtpConnection().endCall();
 218        }
 219    }
 220
 221    private void retractSessionProposal() {
 222        final Intent intent = getIntent();
 223        final String action = intent.getAction();
 224        final Account account = extractAccount(intent);
 225        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
 226        final String state = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
 227        if (!Intent.ACTION_VIEW.equals(action) || state == null || !END_CARD.contains(RtpEndUserState.valueOf(state))) {
 228            resetIntent(account, with, RtpEndUserState.RETRACTED, actionToMedia(intent.getAction()));
 229        }
 230        xmppConnectionService.getJingleConnectionManager().retractSessionProposal(account, with.asBareJid());
 231    }
 232
 233    private void rejectCall(View view) {
 234        requireRtpConnection().rejectCall();
 235        finish();
 236    }
 237
 238    private void acceptCall(View view) {
 239        requestPermissionsAndAcceptCall();
 240    }
 241
 242    private void requestPermissionsAndAcceptCall() {
 243        final List<String> permissions;
 244        if (getMedia().contains(Media.VIDEO)) {
 245            permissions = ImmutableList.of(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO);
 246        } else {
 247            permissions = ImmutableList.of(Manifest.permission.RECORD_AUDIO);
 248        }
 249        if (PermissionUtils.hasPermission(this, permissions, REQUEST_ACCEPT_CALL)) {
 250            putScreenInCallMode();
 251            checkRecorderAndAcceptCall();
 252        }
 253    }
 254
 255    private void checkRecorderAndAcceptCall() {
 256        checkMicrophoneAvailability();
 257        try {
 258            requireRtpConnection().acceptCall();
 259        } catch (final IllegalStateException e) {
 260            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
 261        }
 262    }
 263
 264    private void checkMicrophoneAvailability() {
 265        new Thread(() -> {
 266            final long start = SystemClock.elapsedRealtime();
 267            final boolean isMicrophoneAvailable = AppRTCAudioManager.isMicrophoneAvailable();
 268            final long stop = SystemClock.elapsedRealtime();
 269            Log.d(Config.LOGTAG, "checking microphone availability took " + (stop - start) + "ms");
 270            if (isMicrophoneAvailable) {
 271                return;
 272            }
 273            runOnUiThread(() -> Toast.makeText(this, R.string.microphone_unavailable, Toast.LENGTH_LONG).show());
 274        }
 275        ).start();
 276    }
 277
 278    private void putScreenInCallMode() {
 279        putScreenInCallMode(requireRtpConnection().getMedia());
 280    }
 281
 282    private void putScreenInCallMode(final Set<Media> media) {
 283        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 284        if (!media.contains(Media.VIDEO)) {
 285            final JingleRtpConnection rtpConnection = rtpConnectionReference != null ? rtpConnectionReference.get() : null;
 286            final AppRTCAudioManager audioManager = rtpConnection == null ? null : rtpConnection.getAudioManager();
 287            if (audioManager == null || audioManager.getSelectedAudioDevice() == AppRTCAudioManager.AudioDevice.EARPIECE) {
 288                acquireProximityWakeLock();
 289            }
 290        }
 291    }
 292
 293    @SuppressLint("WakelockTimeout")
 294    private void acquireProximityWakeLock() {
 295        final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
 296        if (powerManager == null) {
 297            Log.e(Config.LOGTAG, "power manager not available");
 298            return;
 299        }
 300        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 301            if (this.mProximityWakeLock == null) {
 302                this.mProximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, PROXIMITY_WAKE_LOCK_TAG);
 303            }
 304            if (!this.mProximityWakeLock.isHeld()) {
 305                Log.d(Config.LOGTAG, "acquiring proximity wake lock");
 306                this.mProximityWakeLock.acquire();
 307            }
 308        }
 309    }
 310
 311    private void releaseProximityWakeLock() {
 312        if (this.mProximityWakeLock != null && mProximityWakeLock.isHeld()) {
 313            Log.d(Config.LOGTAG, "releasing proximity wake lock");
 314            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 315                this.mProximityWakeLock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY);
 316            } else {
 317                this.mProximityWakeLock.release();
 318            }
 319            this.mProximityWakeLock = null;
 320        }
 321    }
 322
 323    private void putProximityWakeLockInProperState(final AppRTCAudioManager.AudioDevice audioDevice) {
 324        if (audioDevice == AppRTCAudioManager.AudioDevice.EARPIECE) {
 325            acquireProximityWakeLock();
 326        } else {
 327            releaseProximityWakeLock();
 328        }
 329    }
 330
 331    @Override
 332    protected void refreshUiReal() {
 333
 334    }
 335
 336    @Override
 337    public void onNewIntent(final Intent intent) {
 338        Log.d(Config.LOGTAG, this.getClass().getName() + ".onNewIntent()");
 339        super.onNewIntent(intent);
 340        setIntent(intent);
 341        if (xmppConnectionService == null) {
 342            Log.d(Config.LOGTAG, "RtpSessionActivity: background service wasn't bound in onNewIntent()");
 343            return;
 344        }
 345        final Account account = extractAccount(intent);
 346        final String action = intent.getAction();
 347        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
 348        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
 349        if (sessionId != null) {
 350            Log.d(Config.LOGTAG, "reinitializing from onNewIntent()");
 351            if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
 352                return;
 353            }
 354            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
 355                Log.d(Config.LOGTAG, "accepting call from onNewIntent()");
 356                requestPermissionsAndAcceptCall();
 357                resetIntent(intent.getExtras());
 358            }
 359        } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
 360            proposeJingleRtpSession(account, with, actionToMedia(action));
 361            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
 362        } else {
 363            throw new IllegalStateException("received onNewIntent without sessionId");
 364        }
 365    }
 366
 367    @Override
 368    void onBackendConnected() {
 369        final Intent intent = getIntent();
 370        final String action = intent.getAction();
 371        final Account account = extractAccount(intent);
 372        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
 373        final String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
 374        if (sessionId != null) {
 375            if (initializeActivityWithRunningRtpSession(account, with, sessionId)) {
 376                return;
 377            }
 378            if (ACTION_ACCEPT_CALL.equals(intent.getAction())) {
 379                Log.d(Config.LOGTAG, "intent action was accept");
 380                requestPermissionsAndAcceptCall();
 381                resetIntent(intent.getExtras());
 382            }
 383        } else if (asList(ACTION_MAKE_VIDEO_CALL, ACTION_MAKE_VOICE_CALL).contains(action)) {
 384            proposeJingleRtpSession(account, with, actionToMedia(action));
 385            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
 386        } else if (Intent.ACTION_VIEW.equals(action)) {
 387            final String extraLastState = intent.getStringExtra(EXTRA_LAST_REPORTED_STATE);
 388            final RtpEndUserState state = extraLastState == null ? null : RtpEndUserState.valueOf(extraLastState);
 389            if (state != null) {
 390                Log.d(Config.LOGTAG, "restored last state from intent extra");
 391                updateButtonConfiguration(state);
 392                updateVerifiedShield(false);
 393                updateStateDisplay(state);
 394                updateProfilePicture(state);
 395                invalidateOptionsMenu();
 396            }
 397            binding.with.setText(account.getRoster().getContact(with).getDisplayName());
 398            if (xmppConnectionService.getJingleConnectionManager().fireJingleRtpConnectionStateUpdates()) {
 399                return;
 400            }
 401            if (END_CARD.contains(state) || xmppConnectionService.getJingleConnectionManager().hasMatchingProposal(account, with)) {
 402                return;
 403            }
 404            Log.d(Config.LOGTAG, "restored state (" + state + ") was not an end card. finishing");
 405            finish();
 406        }
 407    }
 408
 409    private void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
 410        checkMicrophoneAvailability();
 411        if (with.isBareJid()) {
 412            xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(account, with, media);
 413        } else {
 414            final String sessionId = xmppConnectionService.getJingleConnectionManager().initializeRtpSession(account, with, media);
 415            initializeActivityWithRunningRtpSession(account, with, sessionId);
 416            resetIntent(account, with, sessionId);
 417        }
 418        putScreenInCallMode(media);
 419    }
 420
 421    @Override
 422    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 423        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
 424        if (PermissionUtils.allGranted(grantResults)) {
 425            if (requestCode == REQUEST_ACCEPT_CALL) {
 426                checkRecorderAndAcceptCall();
 427            }
 428        } else {
 429            @StringRes int res;
 430            final String firstDenied = getFirstDenied(grantResults, permissions);
 431            if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) {
 432                res = R.string.no_microphone_permission;
 433            } else if (Manifest.permission.CAMERA.equals(firstDenied)) {
 434                res = R.string.no_camera_permission;
 435            } else {
 436                throw new IllegalStateException("Invalid permission result request");
 437            }
 438            Toast.makeText(this, getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
 439        }
 440    }
 441
 442    @Override
 443    public void onStart() {
 444        super.onStart();
 445        mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
 446    }
 447
 448    @Override
 449    public void onStop() {
 450        mHandler.removeCallbacks(mTickExecutor);
 451        binding.remoteVideo.release();
 452        binding.localVideo.release();
 453        final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
 454        final JingleRtpConnection jingleRtpConnection = weakReference == null ? null : weakReference.get();
 455        if (jingleRtpConnection != null) {
 456            releaseVideoTracks(jingleRtpConnection);
 457        }
 458        releaseProximityWakeLock();
 459        super.onStop();
 460    }
 461
 462    private void releaseVideoTracks(final JingleRtpConnection jingleRtpConnection) {
 463        final Optional<VideoTrack> remoteVideo = jingleRtpConnection.getRemoteVideoTrack();
 464        if (remoteVideo.isPresent()) {
 465            remoteVideo.get().removeSink(binding.remoteVideo);
 466        }
 467        final Optional<VideoTrack> localVideo = jingleRtpConnection.getLocalVideoTrack();
 468        if (localVideo.isPresent()) {
 469            localVideo.get().removeSink(binding.localVideo);
 470        }
 471    }
 472
 473    @Override
 474    public void onBackPressed() {
 475        if (isConnected()) {
 476            if (switchToPictureInPicture()) {
 477                return;
 478            }
 479        } else {
 480            endCall();
 481        }
 482        super.onBackPressed();
 483    }
 484
 485    @Override
 486    public void onUserLeaveHint() {
 487        super.onUserLeaveHint();
 488        if (switchToPictureInPicture()) {
 489            return;
 490        }
 491        //TODO apparently this method is not getting called on Android 10 when using the task switcher
 492        final boolean emptyReference = rtpConnectionReference == null || rtpConnectionReference.get() == null;
 493        if (emptyReference && xmppConnectionService != null) {
 494            retractSessionProposal();
 495        }
 496    }
 497
 498    private boolean isConnected() {
 499        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 500        return connection != null && connection.getEndUserState() == RtpEndUserState.CONNECTED;
 501    }
 502
 503    private boolean switchToPictureInPicture() {
 504        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && deviceSupportsPictureInPicture()) {
 505            if (shouldBePictureInPicture()) {
 506                startPictureInPicture();
 507                return true;
 508            }
 509        }
 510        return false;
 511    }
 512
 513    @RequiresApi(api = Build.VERSION_CODES.O)
 514    private void startPictureInPicture() {
 515        try {
 516            enterPictureInPictureMode(
 517                    new PictureInPictureParams.Builder()
 518                            .setAspectRatio(new Rational(10, 16))
 519                            .build()
 520            );
 521        } catch (final IllegalStateException e) {
 522            //this sometimes happens on Samsung phones (possibly when Knox is enabled)
 523            Log.w(Config.LOGTAG, "unable to enter picture in picture mode", e);
 524        }
 525    }
 526
 527    private boolean deviceSupportsPictureInPicture() {
 528        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 529            return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
 530        } else {
 531            return false;
 532        }
 533    }
 534
 535    private boolean shouldBePictureInPicture() {
 536        try {
 537            final JingleRtpConnection rtpConnection = requireRtpConnection();
 538            return rtpConnection.getMedia().contains(Media.VIDEO) && Arrays.asList(
 539                    RtpEndUserState.ACCEPTING_CALL,
 540                    RtpEndUserState.CONNECTING,
 541                    RtpEndUserState.CONNECTED
 542            ).contains(rtpConnection.getEndUserState());
 543        } catch (final IllegalStateException e) {
 544            return false;
 545        }
 546    }
 547
 548    private boolean initializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
 549        final WeakReference<JingleRtpConnection> reference = xmppConnectionService.getJingleConnectionManager()
 550                .findJingleRtpConnection(account, with, sessionId);
 551        if (reference == null || reference.get() == null) {
 552            final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession = xmppConnectionService
 553                    .getJingleConnectionManager().getTerminalSessionState(with, sessionId);
 554            if (terminatedRtpSession == null) {
 555                throw new IllegalStateException("failed to initialize activity with running rtp session. session not found");
 556            }
 557            initializeWithTerminatedSessionState(account, with, terminatedRtpSession);
 558            return true;
 559        }
 560        this.rtpConnectionReference = reference;
 561        final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
 562        final boolean verified = requireRtpConnection().isVerified();
 563        if (currentState == RtpEndUserState.ENDED) {
 564            reference.get().throwStateTransitionException();
 565            finish();
 566            return true;
 567        }
 568        final Set<Media> media = getMedia();
 569        if (currentState == RtpEndUserState.INCOMING_CALL) {
 570            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 571        }
 572        if (JingleRtpConnection.STATES_SHOWING_ONGOING_CALL.contains(requireRtpConnection().getState())) {
 573            putScreenInCallMode();
 574        }
 575        binding.with.setText(getWith().getDisplayName());
 576        updateVideoViews(currentState);
 577        updateStateDisplay(currentState, media);
 578        updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
 579        updateButtonConfiguration(currentState, media);
 580        updateProfilePicture(currentState);
 581        invalidateOptionsMenu();
 582        return false;
 583    }
 584
 585    private void initializeWithTerminatedSessionState(final Account account, final Jid with, final JingleConnectionManager.TerminatedRtpSession terminatedRtpSession) {
 586        Log.d(Config.LOGTAG, "initializeWithTerminatedSessionState()");
 587        if (terminatedRtpSession.state == RtpEndUserState.ENDED) {
 588            finish();
 589            return;
 590        }
 591        RtpEndUserState state = terminatedRtpSession.state;
 592        resetIntent(account, with, terminatedRtpSession.state, terminatedRtpSession.media);
 593        updateButtonConfiguration(state);
 594        updateStateDisplay(state);
 595        updateProfilePicture(state);
 596        updateCallDuration();
 597        updateVerifiedShield(false);
 598        invalidateOptionsMenu();
 599        binding.with.setText(account.getRoster().getContact(with).getDisplayName());
 600    }
 601
 602    private void reInitializeActivityWithRunningRtpSession(final Account account, Jid with, String sessionId) {
 603        runOnUiThread(() -> initializeActivityWithRunningRtpSession(account, with, sessionId));
 604        resetIntent(account, with, sessionId);
 605    }
 606
 607    private void resetIntent(final Account account, final Jid with, final String sessionId) {
 608        final Intent intent = new Intent(Intent.ACTION_VIEW);
 609        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
 610        intent.putExtra(EXTRA_WITH, with.toEscapedString());
 611        intent.putExtra(EXTRA_SESSION_ID, sessionId);
 612        setIntent(intent);
 613    }
 614
 615    private void ensureSurfaceViewRendererIsSetup(final SurfaceViewRenderer surfaceViewRenderer) {
 616        surfaceViewRenderer.setVisibility(View.VISIBLE);
 617        try {
 618            surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
 619        } catch (IllegalStateException e) {
 620            Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
 621        }
 622        surfaceViewRenderer.setEnableHardwareScaler(true);
 623    }
 624
 625    private void updateStateDisplay(final RtpEndUserState state) {
 626        updateStateDisplay(state, Collections.emptySet());
 627    }
 628
 629    private void updateStateDisplay(final RtpEndUserState state, final Set<Media> media) {
 630        switch (state) {
 631            case INCOMING_CALL:
 632                Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
 633                if (media.contains(Media.VIDEO)) {
 634                    setTitle(R.string.rtp_state_incoming_video_call);
 635                } else {
 636                    setTitle(R.string.rtp_state_incoming_call);
 637                }
 638                break;
 639            case CONNECTING:
 640                setTitle(R.string.rtp_state_connecting);
 641                break;
 642            case CONNECTED:
 643                setTitle(R.string.rtp_state_connected);
 644                break;
 645            case ACCEPTING_CALL:
 646                setTitle(R.string.rtp_state_accepting_call);
 647                break;
 648            case ENDING_CALL:
 649                setTitle(R.string.rtp_state_ending_call);
 650                break;
 651            case FINDING_DEVICE:
 652                setTitle(R.string.rtp_state_finding_device);
 653                break;
 654            case RINGING:
 655                setTitle(R.string.rtp_state_ringing);
 656                break;
 657            case DECLINED_OR_BUSY:
 658                setTitle(R.string.rtp_state_declined_or_busy);
 659                break;
 660            case CONNECTIVITY_ERROR:
 661                setTitle(R.string.rtp_state_connectivity_error);
 662                break;
 663            case CONNECTIVITY_LOST_ERROR:
 664                setTitle(R.string.rtp_state_connectivity_lost_error);
 665                break;
 666            case RETRACTED:
 667                setTitle(R.string.rtp_state_retracted);
 668                break;
 669            case APPLICATION_ERROR:
 670                setTitle(R.string.rtp_state_application_failure);
 671                break;
 672            case ENDED:
 673                throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
 674            default:
 675                throw new IllegalStateException(String.format("State %s has not been handled in UI", state));
 676        }
 677    }
 678
 679    private void updateVerifiedShield(final boolean verified) {
 680        if (isPictureInPicture()) {
 681            this.binding.verified.setVisibility(View.GONE);
 682            return;
 683        }
 684        this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
 685    }
 686
 687    private void updateProfilePicture(final RtpEndUserState state) {
 688        updateProfilePicture(state, null);
 689    }
 690
 691    private void updateProfilePicture(final RtpEndUserState state, final Contact contact) {
 692        if (state == RtpEndUserState.INCOMING_CALL || state == RtpEndUserState.ACCEPTING_CALL) {
 693            final boolean show = getResources().getBoolean(R.bool.show_avatar_incoming_call);
 694            if (show) {
 695                binding.contactPhoto.setVisibility(View.VISIBLE);
 696                if (contact == null) {
 697                    AvatarWorkerTask.loadAvatar(getWith(), binding.contactPhoto, R.dimen.publish_avatar_size);
 698                } else {
 699                    AvatarWorkerTask.loadAvatar(contact, binding.contactPhoto, R.dimen.publish_avatar_size);
 700                }
 701            } else {
 702                binding.contactPhoto.setVisibility(View.GONE);
 703            }
 704        } else {
 705            binding.contactPhoto.setVisibility(View.GONE);
 706        }
 707    }
 708
 709    private Set<Media> getMedia() {
 710        return requireRtpConnection().getMedia();
 711    }
 712
 713    private void updateButtonConfiguration(final RtpEndUserState state) {
 714        updateButtonConfiguration(state, Collections.emptySet());
 715    }
 716
 717    @SuppressLint("RestrictedApi")
 718    private void updateButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
 719        if (state == RtpEndUserState.ENDING_CALL || isPictureInPicture()) {
 720            this.binding.rejectCall.setVisibility(View.INVISIBLE);
 721            this.binding.endCall.setVisibility(View.INVISIBLE);
 722            this.binding.acceptCall.setVisibility(View.INVISIBLE);
 723        } else if (state == RtpEndUserState.INCOMING_CALL) {
 724            this.binding.rejectCall.setContentDescription(getString(R.string.dismiss_call));
 725            this.binding.rejectCall.setOnClickListener(this::rejectCall);
 726            this.binding.rejectCall.setImageResource(R.drawable.ic_call_end_white_48dp);
 727            this.binding.rejectCall.setVisibility(View.VISIBLE);
 728            this.binding.endCall.setVisibility(View.INVISIBLE);
 729            this.binding.acceptCall.setContentDescription(getString(R.string.answer_call));
 730            this.binding.acceptCall.setOnClickListener(this::acceptCall);
 731            this.binding.acceptCall.setImageResource(R.drawable.ic_call_white_48dp);
 732            this.binding.acceptCall.setVisibility(View.VISIBLE);
 733        } else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
 734            this.binding.rejectCall.setContentDescription(getString(R.string.exit));
 735            this.binding.rejectCall.setOnClickListener(this::exit);
 736            this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
 737            this.binding.rejectCall.setVisibility(View.VISIBLE);
 738            this.binding.endCall.setVisibility(View.INVISIBLE);
 739            this.binding.acceptCall.setContentDescription(getString(R.string.record_voice_mail));
 740            this.binding.acceptCall.setOnClickListener(this::recordVoiceMail);
 741            this.binding.acceptCall.setImageResource(R.drawable.ic_voicemail_white_24dp);
 742            this.binding.acceptCall.setVisibility(View.VISIBLE);
 743        } else if (asList(
 744                RtpEndUserState.CONNECTIVITY_ERROR,
 745                RtpEndUserState.CONNECTIVITY_LOST_ERROR,
 746                RtpEndUserState.APPLICATION_ERROR,
 747                RtpEndUserState.RETRACTED
 748        ).contains(state)) {
 749            this.binding.rejectCall.setContentDescription(getString(R.string.exit));
 750            this.binding.rejectCall.setOnClickListener(this::exit);
 751            this.binding.rejectCall.setImageResource(R.drawable.ic_clear_white_48dp);
 752            this.binding.rejectCall.setVisibility(View.VISIBLE);
 753            this.binding.endCall.setVisibility(View.INVISIBLE);
 754            this.binding.acceptCall.setContentDescription(getString(R.string.try_again));
 755            this.binding.acceptCall.setOnClickListener(this::retry);
 756            this.binding.acceptCall.setImageResource(R.drawable.ic_replay_white_48dp);
 757            this.binding.acceptCall.setVisibility(View.VISIBLE);
 758        } else {
 759            this.binding.rejectCall.setVisibility(View.INVISIBLE);
 760            this.binding.endCall.setContentDescription(getString(R.string.hang_up));
 761            this.binding.endCall.setOnClickListener(this::endCall);
 762            this.binding.endCall.setImageResource(R.drawable.ic_call_end_white_48dp);
 763            this.binding.endCall.setVisibility(View.VISIBLE);
 764            this.binding.acceptCall.setVisibility(View.INVISIBLE);
 765        }
 766        updateInCallButtonConfiguration(state, media);
 767    }
 768
 769    private boolean isPictureInPicture() {
 770        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
 771            return isInPictureInPictureMode();
 772        } else {
 773            return false;
 774        }
 775    }
 776
 777    private void updateInCallButtonConfiguration() {
 778        updateInCallButtonConfiguration(requireRtpConnection().getEndUserState(), requireRtpConnection().getMedia());
 779    }
 780
 781    @SuppressLint("RestrictedApi")
 782    private void updateInCallButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
 783        if (state == RtpEndUserState.CONNECTED && !isPictureInPicture()) {
 784            Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
 785            if (media.contains(Media.VIDEO)) {
 786                final JingleRtpConnection rtpConnection = requireRtpConnection();
 787                updateInCallButtonConfigurationVideo(rtpConnection.isVideoEnabled(), rtpConnection.isCameraSwitchable());
 788            } else {
 789                final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
 790                updateInCallButtonConfigurationSpeaker(
 791                        audioManager.getSelectedAudioDevice(),
 792                        audioManager.getAudioDevices().size()
 793                );
 794                this.binding.inCallActionFarRight.setVisibility(View.GONE);
 795            }
 796            if (media.contains(Media.AUDIO)) {
 797                updateInCallButtonConfigurationMicrophone(requireRtpConnection().isMicrophoneEnabled());
 798            } else {
 799                this.binding.inCallActionLeft.setVisibility(View.GONE);
 800            }
 801        } else {
 802            this.binding.inCallActionLeft.setVisibility(View.GONE);
 803            this.binding.inCallActionRight.setVisibility(View.GONE);
 804            this.binding.inCallActionFarRight.setVisibility(View.GONE);
 805        }
 806    }
 807
 808    @SuppressLint("RestrictedApi")
 809    private void updateInCallButtonConfigurationSpeaker(final AppRTCAudioManager.AudioDevice selectedAudioDevice, final int numberOfChoices) {
 810        switch (selectedAudioDevice) {
 811            case EARPIECE:
 812                this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_off_black_24dp);
 813                if (numberOfChoices >= 2) {
 814                    this.binding.inCallActionRight.setOnClickListener(this::switchToSpeaker);
 815                } else {
 816                    this.binding.inCallActionRight.setOnClickListener(null);
 817                    this.binding.inCallActionRight.setClickable(false);
 818                }
 819                break;
 820            case WIRED_HEADSET:
 821                this.binding.inCallActionRight.setImageResource(R.drawable.ic_headset_black_24dp);
 822                this.binding.inCallActionRight.setOnClickListener(null);
 823                this.binding.inCallActionRight.setClickable(false);
 824                break;
 825            case SPEAKER_PHONE:
 826                this.binding.inCallActionRight.setImageResource(R.drawable.ic_volume_up_black_24dp);
 827                if (numberOfChoices >= 2) {
 828                    this.binding.inCallActionRight.setOnClickListener(this::switchToEarpiece);
 829                } else {
 830                    this.binding.inCallActionRight.setOnClickListener(null);
 831                    this.binding.inCallActionRight.setClickable(false);
 832                }
 833                break;
 834            case BLUETOOTH:
 835                this.binding.inCallActionRight.setImageResource(R.drawable.ic_bluetooth_audio_black_24dp);
 836                this.binding.inCallActionRight.setOnClickListener(null);
 837                this.binding.inCallActionRight.setClickable(false);
 838                break;
 839        }
 840        this.binding.inCallActionRight.setVisibility(View.VISIBLE);
 841    }
 842
 843    @SuppressLint("RestrictedApi")
 844    private void updateInCallButtonConfigurationVideo(final boolean videoEnabled, final boolean isCameraSwitchable) {
 845        this.binding.inCallActionRight.setVisibility(View.VISIBLE);
 846        if (isCameraSwitchable) {
 847            this.binding.inCallActionFarRight.setImageResource(R.drawable.ic_flip_camera_android_black_24dp);
 848            this.binding.inCallActionFarRight.setVisibility(View.VISIBLE);
 849            this.binding.inCallActionFarRight.setOnClickListener(this::switchCamera);
 850        } else {
 851            this.binding.inCallActionFarRight.setVisibility(View.GONE);
 852        }
 853        if (videoEnabled) {
 854            this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_black_24dp);
 855            this.binding.inCallActionRight.setOnClickListener(this::disableVideo);
 856        } else {
 857            this.binding.inCallActionRight.setImageResource(R.drawable.ic_videocam_off_black_24dp);
 858            this.binding.inCallActionRight.setOnClickListener(this::enableVideo);
 859        }
 860    }
 861
 862    private void switchCamera(final View view) {
 863        Futures.addCallback(requireRtpConnection().switchCamera(), new FutureCallback<Boolean>() {
 864            @Override
 865            public void onSuccess(@NullableDecl Boolean isFrontCamera) {
 866                binding.localVideo.setMirror(isFrontCamera);
 867            }
 868
 869            @Override
 870            public void onFailure(@NonNull final Throwable throwable) {
 871                Log.d(Config.LOGTAG, "could not switch camera", Throwables.getRootCause(throwable));
 872                Toast.makeText(RtpSessionActivity.this, R.string.could_not_switch_camera, Toast.LENGTH_LONG).show();
 873            }
 874        }, MainThreadExecutor.getInstance());
 875    }
 876
 877    private void enableVideo(View view) {
 878        requireRtpConnection().setVideoEnabled(true);
 879        updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
 880    }
 881
 882    private void disableVideo(View view) {
 883        requireRtpConnection().setVideoEnabled(false);
 884        updateInCallButtonConfigurationVideo(false, requireRtpConnection().isCameraSwitchable());
 885
 886    }
 887
 888    @SuppressLint("RestrictedApi")
 889    private void updateInCallButtonConfigurationMicrophone(final boolean microphoneEnabled) {
 890        if (microphoneEnabled) {
 891            this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_black_24dp);
 892            this.binding.inCallActionLeft.setOnClickListener(this::disableMicrophone);
 893        } else {
 894            this.binding.inCallActionLeft.setImageResource(R.drawable.ic_mic_off_black_24dp);
 895            this.binding.inCallActionLeft.setOnClickListener(this::enableMicrophone);
 896        }
 897        this.binding.inCallActionLeft.setVisibility(View.VISIBLE);
 898    }
 899
 900    private void updateCallDuration() {
 901        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 902        if (connection == null || connection.getMedia().contains(Media.VIDEO)) {
 903            this.binding.duration.setVisibility(View.GONE);
 904            return;
 905        }
 906        final long rtpConnectionStarted = connection.getRtpConnectionStarted();
 907        final long rtpConnectionEnded = connection.getRtpConnectionEnded();
 908        if (rtpConnectionStarted != 0) {
 909            final long ended = rtpConnectionEnded == 0 ? SystemClock.elapsedRealtime() : rtpConnectionEnded;
 910            this.binding.duration.setText(TimeFrameUtils.formatTimePassed(rtpConnectionStarted, ended, false));
 911            this.binding.duration.setVisibility(View.VISIBLE);
 912        } else {
 913            this.binding.duration.setVisibility(View.GONE);
 914        }
 915    }
 916
 917    private void updateVideoViews(final RtpEndUserState state) {
 918        if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
 919            binding.localVideo.setVisibility(View.GONE);
 920            binding.localVideo.release();
 921            binding.remoteVideo.setVisibility(View.GONE);
 922            binding.remoteVideo.release();
 923            binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
 924            if (isPictureInPicture()) {
 925                binding.appBarLayout.setVisibility(View.GONE);
 926                binding.pipPlaceholder.setVisibility(View.VISIBLE);
 927                if (state == RtpEndUserState.APPLICATION_ERROR || state == RtpEndUserState.CONNECTIVITY_ERROR) {
 928                    binding.pipWarning.setVisibility(View.VISIBLE);
 929                    binding.pipWaiting.setVisibility(View.GONE);
 930                } else {
 931                    binding.pipWarning.setVisibility(View.GONE);
 932                    binding.pipWaiting.setVisibility(View.GONE);
 933                }
 934            } else {
 935                binding.appBarLayout.setVisibility(View.VISIBLE);
 936                binding.pipPlaceholder.setVisibility(View.GONE);
 937            }
 938            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
 939            return;
 940        }
 941        if (isPictureInPicture() && (state == RtpEndUserState.CONNECTING || state == RtpEndUserState.ACCEPTING_CALL)) {
 942            binding.localVideo.setVisibility(View.GONE);
 943            binding.remoteVideo.setVisibility(View.GONE);
 944            binding.appBarLayout.setVisibility(View.GONE);
 945            binding.pipPlaceholder.setVisibility(View.VISIBLE);
 946            binding.pipWarning.setVisibility(View.GONE);
 947            binding.pipWaiting.setVisibility(View.VISIBLE);
 948            binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
 949            return;
 950        }
 951        final Optional<VideoTrack> localVideoTrack = getLocalVideoTrack();
 952        if (localVideoTrack.isPresent() && !isPictureInPicture()) {
 953            ensureSurfaceViewRendererIsSetup(binding.localVideo);
 954            //paint local view over remote view
 955            binding.localVideo.setZOrderMediaOverlay(true);
 956            binding.localVideo.setMirror(requireRtpConnection().isFrontCamera());
 957            addSink(localVideoTrack.get(), binding.localVideo);
 958        } else {
 959            binding.localVideo.setVisibility(View.GONE);
 960        }
 961        final Optional<VideoTrack> remoteVideoTrack = getRemoteVideoTrack();
 962        if (remoteVideoTrack.isPresent()) {
 963            ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
 964            addSink(remoteVideoTrack.get(), binding.remoteVideo);
 965            if (state == RtpEndUserState.CONNECTED) {
 966                binding.appBarLayout.setVisibility(View.GONE);
 967                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
 968            } else {
 969                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
 970                binding.remoteVideo.setVisibility(View.GONE);
 971            }
 972            if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
 973                binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
 974            } else {
 975                binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
 976            }
 977        } else {
 978            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
 979            binding.remoteVideo.setVisibility(View.GONE);
 980            binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
 981        }
 982    }
 983
 984    private Optional<VideoTrack> getLocalVideoTrack() {
 985        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 986        if (connection == null) {
 987            return Optional.absent();
 988        }
 989        return connection.getLocalVideoTrack();
 990    }
 991
 992    private Optional<VideoTrack> getRemoteVideoTrack() {
 993        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
 994        if (connection == null) {
 995            return Optional.absent();
 996        }
 997        return connection.getRemoteVideoTrack();
 998    }
 999
1000    private void disableMicrophone(View view) {
1001        final JingleRtpConnection rtpConnection = requireRtpConnection();
1002        if (rtpConnection.setMicrophoneEnabled(false)) {
1003            updateInCallButtonConfiguration();
1004        }
1005    }
1006
1007    private void enableMicrophone(View view) {
1008        final JingleRtpConnection rtpConnection = requireRtpConnection();
1009        if (rtpConnection.setMicrophoneEnabled(true)) {
1010            updateInCallButtonConfiguration();
1011        }
1012    }
1013
1014    private void switchToEarpiece(View view) {
1015        requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
1016        acquireProximityWakeLock();
1017    }
1018
1019    private void switchToSpeaker(View view) {
1020        requireRtpConnection().getAudioManager().setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
1021        releaseProximityWakeLock();
1022    }
1023
1024    private void retry(View view) {
1025        final Intent intent = getIntent();
1026        final Account account = extractAccount(intent);
1027        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1028        final String lastAction = intent.getStringExtra(EXTRA_LAST_ACTION);
1029        final String action = intent.getAction();
1030        final Set<Media> media = actionToMedia(lastAction == null ? action : lastAction);
1031        this.rtpConnectionReference = null;
1032        Log.d(Config.LOGTAG, "attempting retry with " + with.toEscapedString());
1033        proposeJingleRtpSession(account, with, media);
1034    }
1035
1036    private void exit(final View view) {
1037        finish();
1038    }
1039
1040    private void recordVoiceMail(final View view) {
1041        final Intent intent = getIntent();
1042        final Account account = extractAccount(intent);
1043        final Jid with = Jid.ofEscaped(intent.getStringExtra(EXTRA_WITH));
1044        final Conversation conversation = xmppConnectionService.findOrCreateConversation(account, with, false, true);
1045        final Intent launchIntent = new Intent(this, ConversationsActivity.class);
1046        launchIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1047        launchIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
1048        launchIntent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1049        launchIntent.putExtra(ConversationsActivity.EXTRA_POST_INIT_ACTION, ConversationsActivity.POST_ACTION_RECORD_VOICE);
1050        startActivity(launchIntent);
1051        finish();
1052    }
1053
1054    private Contact getWith() {
1055        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1056        final Account account = id.account;
1057        return account.getRoster().getContact(id.with);
1058    }
1059
1060    private JingleRtpConnection requireRtpConnection() {
1061        final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
1062        if (connection == null) {
1063            throw new IllegalStateException("No RTP connection found");
1064        }
1065        return connection;
1066    }
1067
1068    @Override
1069    public void onJingleRtpConnectionUpdate(Account account, Jid with, final String sessionId, RtpEndUserState state) {
1070        Log.d(Config.LOGTAG, "onJingleRtpConnectionUpdate(" + state + ")");
1071        if (END_CARD.contains(state)) {
1072            Log.d(Config.LOGTAG, "end card reached");
1073            releaseProximityWakeLock();
1074            runOnUiThread(() -> getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
1075        }
1076        if (with.isBareJid()) {
1077            updateRtpSessionProposalState(account, with, state);
1078            return;
1079        }
1080        if (this.rtpConnectionReference == null) {
1081            if (END_CARD.contains(state)) {
1082                Log.d(Config.LOGTAG, "not reinitializing session");
1083                return;
1084            }
1085            //this happens when going from proposed session to actual session
1086            reInitializeActivityWithRunningRtpSession(account, with, sessionId);
1087            return;
1088        }
1089        final AbstractJingleConnection.Id id = requireRtpConnection().getId();
1090        final boolean verified = requireRtpConnection().isVerified();
1091        final Set<Media> media = getMedia();
1092        final Contact contact = getWith();
1093        if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
1094            if (state == RtpEndUserState.ENDED) {
1095                finish();
1096                return;
1097            }
1098            runOnUiThread(() -> {
1099                updateStateDisplay(state, media);
1100                updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
1101                updateButtonConfiguration(state, media);
1102                updateVideoViews(state);
1103                updateProfilePicture(state, contact);
1104                invalidateOptionsMenu();
1105            });
1106            if (END_CARD.contains(state)) {
1107                final JingleRtpConnection rtpConnection = requireRtpConnection();
1108                resetIntent(account, with, state, rtpConnection.getMedia());
1109                releaseVideoTracks(rtpConnection);
1110                this.rtpConnectionReference = null;
1111            }
1112        } else {
1113            Log.d(Config.LOGTAG, "received update for other rtp session");
1114        }
1115    }
1116
1117    @Override
1118    public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
1119        Log.d(Config.LOGTAG, "onAudioDeviceChanged in activity: selected:" + selectedAudioDevice + ", available:" + availableAudioDevices);
1120        try {
1121            if (getMedia().contains(Media.VIDEO)) {
1122                Log.d(Config.LOGTAG, "nothing to do; in video mode");
1123                return;
1124            }
1125            final RtpEndUserState endUserState = requireRtpConnection().getEndUserState();
1126            if (endUserState == RtpEndUserState.CONNECTED) {
1127                final AppRTCAudioManager audioManager = requireRtpConnection().getAudioManager();
1128                updateInCallButtonConfigurationSpeaker(
1129                        audioManager.getSelectedAudioDevice(),
1130                        audioManager.getAudioDevices().size()
1131                );
1132            } else if (END_CARD.contains(endUserState)) {
1133                Log.d(Config.LOGTAG, "onAudioDeviceChanged() nothing to do because end card has been reached");
1134            } else {
1135                putProximityWakeLockInProperState(selectedAudioDevice);
1136            }
1137        } catch (IllegalStateException e) {
1138            Log.d(Config.LOGTAG, "RTP connection was not available when audio device changed");
1139        }
1140    }
1141
1142    private void updateRtpSessionProposalState(final Account account, final Jid with, final RtpEndUserState state) {
1143        final Intent currentIntent = getIntent();
1144        final String withExtra = currentIntent == null ? null : currentIntent.getStringExtra(EXTRA_WITH);
1145        if (withExtra == null) {
1146            return;
1147        }
1148        if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
1149            runOnUiThread(() -> {
1150                updateVerifiedShield(false);
1151                updateStateDisplay(state);
1152                updateButtonConfiguration(state);
1153                updateProfilePicture(state);
1154                invalidateOptionsMenu();
1155            });
1156            resetIntent(account, with, state, actionToMedia(currentIntent.getAction()));
1157        }
1158    }
1159
1160    private void resetIntent(final Bundle extras) {
1161        final Intent intent = new Intent(Intent.ACTION_VIEW);
1162        intent.putExtras(extras);
1163        setIntent(intent);
1164    }
1165
1166    private void resetIntent(final Account account, Jid with, final RtpEndUserState state, final Set<Media> media) {
1167        final Intent intent = new Intent(Intent.ACTION_VIEW);
1168        intent.putExtra(EXTRA_ACCOUNT, account.getJid().toEscapedString());
1169        if (account.getRoster().getContact(with).getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
1170            intent.putExtra(EXTRA_WITH, with.asBareJid().toEscapedString());
1171        } else {
1172            intent.putExtra(EXTRA_WITH, with.toEscapedString());
1173        }
1174        intent.putExtra(EXTRA_LAST_REPORTED_STATE, state.toString());
1175        intent.putExtra(EXTRA_LAST_ACTION, media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
1176        setIntent(intent);
1177    }
1178}