ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ActivityNotFoundException;
   9import android.content.ClipData;
  10import android.content.DialogInterface;
  11import android.content.DialogInterface.OnClickListener;
  12import android.content.Intent;
  13import android.content.IntentSender.SendIntentException;
  14import android.content.pm.PackageManager;
  15import android.net.Uri;
  16import android.os.Build;
  17import android.os.Bundle;
  18import android.os.Handler;
  19import android.provider.MediaStore;
  20import android.provider.Settings;
  21import android.support.v4.widget.SlidingPaneLayout;
  22import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  23import android.util.Log;
  24import android.util.Pair;
  25import android.view.Gravity;
  26import android.view.KeyEvent;
  27import android.view.Menu;
  28import android.view.MenuItem;
  29import android.view.Surface;
  30import android.view.View;
  31import android.widget.AdapterView;
  32import android.widget.AdapterView.OnItemClickListener;
  33import android.widget.ArrayAdapter;
  34import android.widget.CheckBox;
  35import android.widget.PopupMenu;
  36import android.widget.PopupMenu.OnMenuItemClickListener;
  37import android.widget.Toast;
  38
  39import net.java.otr4j.session.SessionStatus;
  40
  41import org.openintents.openpgp.util.OpenPgpApi;
  42
  43import java.util.ArrayList;
  44import java.util.Iterator;
  45import java.util.List;
  46import java.util.concurrent.atomic.AtomicBoolean;
  47
  48import de.timroes.android.listview.EnhancedListView;
  49import eu.siacs.conversations.Config;
  50import eu.siacs.conversations.R;
  51import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  52import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
  53import eu.siacs.conversations.entities.Account;
  54import eu.siacs.conversations.entities.Blockable;
  55import eu.siacs.conversations.entities.Contact;
  56import eu.siacs.conversations.entities.Conversation;
  57import eu.siacs.conversations.entities.Message;
  58import eu.siacs.conversations.entities.Transferable;
  59import eu.siacs.conversations.persistance.FileBackend;
  60import eu.siacs.conversations.services.XmppConnectionService;
  61import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  62import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  63import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  64import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  65import eu.siacs.conversations.utils.ExceptionHelper;
  66import eu.siacs.conversations.utils.UIHelper;
  67import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  68import eu.siacs.conversations.xmpp.XmppConnection;
  69import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  70import eu.siacs.conversations.xmpp.jid.Jid;
  71
  72public class ConversationActivity extends XmppActivity
  73	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  74
  75	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
  76	public static final String CONVERSATION = "conversationUuid";
  77	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
  78	public static final String TEXT = "text";
  79	public static final String NICK = "nick";
  80	public static final String PRIVATE_MESSAGE = "pm";
  81
  82	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  83	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  84	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  85	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  86	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  87	public static final int REQUEST_START_DOWNLOAD = 0x0210;
  88	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  89	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  90	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  91	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  92	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  93	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  94	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  95	private static final String STATE_PANEL_OPEN = "state_panel_open";
  96	private static final String STATE_PENDING_URI = "state_pending_uri";
  97	private static final String STATE_FIRST_VISIBLE = "first_visible";
  98	private static final String STATE_OFFSET_FROM_TOP = "offset_from_top";
  99
 100	private String mOpenConversation = null;
 101	private boolean mPanelOpen = true;
 102	private AtomicBoolean mShouldPanelBeOpen = new AtomicBoolean(false);
 103	private Pair<Integer,Integer> mScrollPosition = null;
 104	final private List<Uri> mPendingImageUris = new ArrayList<>();
 105	final private List<Uri> mPendingFileUris = new ArrayList<>();
 106	private Uri mPendingGeoUri = null;
 107	private boolean forbidProcessingPendings = false;
 108	private Message mPendingDownloadableMessage = null;
 109
 110	private boolean conversationWasSelectedByKeyboard = false;
 111
 112	private View mContentView;
 113
 114	private List<Conversation> conversationList = new ArrayList<>();
 115	private Conversation swipedConversation = null;
 116	private Conversation mSelectedConversation = null;
 117	private EnhancedListView listView;
 118	private ConversationFragment mConversationFragment;
 119
 120	private ArrayAdapter<Conversation> listAdapter;
 121
 122	private boolean mActivityPaused = false;
 123	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 124	private Pair<Integer, Intent> mPostponedActivityResult;
 125	private boolean mUnprocessedNewIntent = false;
 126
 127	public Conversation getSelectedConversation() {
 128		return this.mSelectedConversation;
 129	}
 130
 131	public void setSelectedConversation(Conversation conversation) {
 132		this.mSelectedConversation = conversation;
 133	}
 134
 135	public void showConversationsOverview() {
 136		if (mContentView instanceof SlidingPaneLayout) {
 137			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 138			mShouldPanelBeOpen.set(true);
 139			mSlidingPaneLayout.openPane();
 140		}
 141	}
 142
 143	@Override
 144	protected String getShareableUri() {
 145		Conversation conversation = getSelectedConversation();
 146		if (conversation != null) {
 147			return conversation.getAccount().getShareableUri();
 148		} else {
 149			return "";
 150		}
 151	}
 152
 153	public void hideConversationsOverview() {
 154		if (mContentView instanceof SlidingPaneLayout) {
 155			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 156			mShouldPanelBeOpen.set(false);
 157			mSlidingPaneLayout.closePane();
 158		}
 159	}
 160
 161	public boolean isConversationsOverviewHideable() {
 162		return mContentView instanceof SlidingPaneLayout;
 163	}
 164
 165	public boolean isConversationsOverviewVisable() {
 166		if (mContentView instanceof SlidingPaneLayout) {
 167			return mShouldPanelBeOpen.get();
 168		} else {
 169			return true;
 170		}
 171	}
 172
 173	@Override
 174	protected void onCreate(final Bundle savedInstanceState) {
 175		super.onCreate(savedInstanceState);
 176		if (savedInstanceState != null) {
 177			mOpenConversation = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 178			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 179			int pos = savedInstanceState.getInt(STATE_FIRST_VISIBLE, -1);
 180			int offset = savedInstanceState.getInt(STATE_OFFSET_FROM_TOP, 1);
 181			if (pos >= 0 && offset <= 0) {
 182				Log.d(Config.LOGTAG,"retrieved scroll position from instanceState "+pos+":"+offset);
 183				mScrollPosition = new Pair<>(pos,offset);
 184			} else {
 185				mScrollPosition = null;
 186			}
 187			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 188			if (pending != null) {
 189				Log.d(Config.LOGTAG,"ConversationsActivity.onCreate() - restoring pending image uri");
 190				mPendingImageUris.clear();
 191				mPendingImageUris.add(Uri.parse(pending));
 192			}
 193		}
 194
 195		setContentView(R.layout.fragment_conversations_overview);
 196
 197		this.mConversationFragment = new ConversationFragment();
 198		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 199		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 200		transaction.commit();
 201
 202		listView = (EnhancedListView) findViewById(R.id.list);
 203		this.listAdapter = new ConversationAdapter(this, conversationList);
 204		listView.setAdapter(this.listAdapter);
 205
 206		final ActionBar actionBar = getActionBar();
 207		if (actionBar != null) {
 208			actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
 209		}
 210
 211		listView.setOnItemClickListener(new OnItemClickListener() {
 212
 213			@Override
 214			public void onItemClick(AdapterView<?> arg0, View clickedView,
 215									int position, long arg3) {
 216				if (getSelectedConversation() != conversationList.get(position)) {
 217					setSelectedConversation(conversationList.get(position));
 218					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 219					conversationWasSelectedByKeyboard = false;
 220				}
 221				hideConversationsOverview();
 222				openConversation();
 223			}
 224		});
 225
 226		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 227
 228			@Override
 229			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 230
 231				final int index = listView.getFirstVisiblePosition();
 232				View v = listView.getChildAt(0);
 233				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 234
 235				try {
 236					swipedConversation = listAdapter.getItem(position);
 237				} catch (IndexOutOfBoundsException e) {
 238					return null;
 239				}
 240				listAdapter.remove(swipedConversation);
 241				xmppConnectionService.markRead(swipedConversation);
 242
 243				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 244				if (position == 0 && listAdapter.getCount() == 0) {
 245					endConversation(swipedConversation, false, true);
 246					return null;
 247				} else if (formerlySelected) {
 248					setSelectedConversation(listAdapter.getItem(0));
 249					ConversationActivity.this.mConversationFragment
 250							.reInit(getSelectedConversation());
 251				}
 252
 253				return new EnhancedListView.Undoable() {
 254
 255					@Override
 256					public void undo() {
 257						listAdapter.insert(swipedConversation, position);
 258						if (formerlySelected) {
 259							setSelectedConversation(swipedConversation);
 260							ConversationActivity.this.mConversationFragment
 261									.reInit(getSelectedConversation());
 262						}
 263						swipedConversation = null;
 264						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 265					}
 266
 267					@Override
 268					public void discard() {
 269						if (!swipedConversation.isRead()
 270								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 271							swipedConversation = null;
 272							return;
 273						}
 274						endConversation(swipedConversation, false, false);
 275						swipedConversation = null;
 276					}
 277
 278					@Override
 279					public String getTitle() {
 280						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 281							return getResources().getString(R.string.title_undo_swipe_out_muc);
 282						} else {
 283							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 284						}
 285					}
 286				};
 287			}
 288		});
 289		listView.enableSwipeToDismiss();
 290		listView.setSwipingLayout(R.id.swipeable_item);
 291		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 292		listView.setUndoHideDelay(5000);
 293		listView.setRequireTouchBeforeDismiss(false);
 294
 295		mContentView = findViewById(R.id.content_view_spl);
 296		if (mContentView == null) {
 297			mContentView = findViewById(R.id.content_view_ll);
 298		}
 299		if (mContentView instanceof SlidingPaneLayout) {
 300			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 301			mSlidingPaneLayout.setShadowResource(R.drawable.es_slidingpane_shadow);
 302			mSlidingPaneLayout.setSliderFadeColor(0);
 303			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 304
 305				@Override
 306				public void onPanelOpened(View arg0) {
 307					mShouldPanelBeOpen.set(true);
 308					updateActionBarTitle();
 309					invalidateOptionsMenu();
 310					hideKeyboard();
 311					if (xmppConnectionServiceBound) {
 312						xmppConnectionService.getNotificationService().setOpenConversation(null);
 313					}
 314					closeContextMenu();
 315				}
 316
 317				@Override
 318				public void onPanelClosed(View arg0) {
 319					mShouldPanelBeOpen.set(false);
 320					listView.discardUndo();
 321					openConversation();
 322				}
 323
 324				@Override
 325				public void onPanelSlide(View arg0, float arg1) {
 326					// TODO Auto-generated method stub
 327
 328				}
 329			});
 330		}
 331	}
 332
 333	@Override
 334	public void switchToConversation(Conversation conversation) {
 335		setSelectedConversation(conversation);
 336		runOnUiThread(new Runnable() {
 337			@Override
 338			public void run() {
 339				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 340				openConversation();
 341			}
 342		});
 343	}
 344
 345	private void updateActionBarTitle() {
 346		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 347	}
 348
 349	private void updateActionBarTitle(boolean titleShouldBeName) {
 350		final ActionBar ab = getActionBar();
 351		final Conversation conversation = getSelectedConversation();
 352		if (ab != null) {
 353			if (titleShouldBeName && conversation != null) {
 354				if ((ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != ActionBar.DISPLAY_HOME_AS_UP) {
 355					ab.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
 356				}
 357				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 358					ab.setTitle(conversation.getName());
 359				} else {
 360					ab.setTitle(conversation.getJid().toBareJid().toString());
 361				}
 362			} else {
 363				if ((ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) == ActionBar.DISPLAY_HOME_AS_UP) {
 364					ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
 365				}
 366				ab.setTitle(R.string.app_name);
 367			}
 368		}
 369	}
 370
 371	private void openConversation() {
 372		this.updateActionBarTitle();
 373		this.invalidateOptionsMenu();
 374		if (xmppConnectionServiceBound) {
 375			final Conversation conversation = getSelectedConversation();
 376			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 377			sendReadMarkerIfNecessary(conversation);
 378		}
 379		listAdapter.notifyDataSetChanged();
 380	}
 381
 382	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 383		if (!mActivityPaused && !mUnprocessedNewIntent && conversation != null) {
 384			xmppConnectionService.sendReadMarker(conversation);
 385		}
 386	}
 387
 388	@Override
 389	public boolean onCreateOptionsMenu(Menu menu) {
 390		getMenuInflater().inflate(R.menu.conversations, menu);
 391		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 392		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 393		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 394		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 395		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 396		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 397		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 398		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 399		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 400		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 401
 402		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 403			menuArchive.setVisible(false);
 404			menuMucDetails.setVisible(false);
 405			menuContactDetails.setVisible(false);
 406			menuSecure.setVisible(false);
 407			menuInviteContact.setVisible(false);
 408			menuAttach.setVisible(false);
 409			menuClearHistory.setVisible(false);
 410			menuMute.setVisible(false);
 411			menuUnmute.setVisible(false);
 412		} else {
 413			menuAdd.setVisible(!isConversationsOverviewHideable());
 414			if (this.getSelectedConversation() != null) {
 415				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 416					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 417						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 418					} else {
 419						menuSecure.setIcon(R.drawable.ic_action_secure);
 420					}
 421				}
 422				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 423					menuContactDetails.setVisible(false);
 424					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 425					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 426					menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
 427				} else {
 428					menuContactDetails.setVisible(!this.getSelectedConversation().withSelf());
 429					menuMucDetails.setVisible(false);
 430					menuSecure.setVisible(Config.multipleEncryptionChoices());
 431					menuInviteContact.setVisible(xmppConnectionService != null && xmppConnectionService.findConferenceServer(getSelectedConversation().getAccount()) != null);
 432				}
 433				if (this.getSelectedConversation().isMuted()) {
 434					menuMute.setVisible(false);
 435				} else {
 436					menuUnmute.setVisible(false);
 437				}
 438			}
 439		}
 440		if (Config.supportOmemo()) {
 441			new Handler().post(new Runnable() {
 442				@Override
 443				public void run() {
 444					View view = findViewById(R.id.action_security);
 445					if (view != null) {
 446						view.setOnLongClickListener(new View.OnLongClickListener() {
 447							@Override
 448							public boolean onLongClick(View v) {
 449								return quickOmemoDebugger(getSelectedConversation());
 450							}
 451						});
 452					}
 453				}
 454			});
 455		}
 456		return super.onCreateOptionsMenu(menu);
 457	}
 458
 459	private boolean quickOmemoDebugger(Conversation c) {
 460		if (c != null) {
 461			boolean single = c.getMode() == Conversation.MODE_SINGLE;
 462			AxolotlService axolotlService = c.getAccount().getAxolotlService();
 463			Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
 464			switch (capabilityJidPair.first) {
 465				case MISSING_PRESENCE:
 466					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_presence_subscription) : getString(R.string.missing_presence_subscription_with_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 467					return true;
 468				case MISSING_KEYS:
 469					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_omemo_keys) : getString(R.string.missing_keys_from_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 470					return true;
 471				case WRONG_CONFIGURATION:
 472					Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
 473					return true;
 474				case NO_MEMBERS:
 475					Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
 476					return true;
 477			}
 478		}
 479		return false;
 480	}
 481
 482	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 483		final Conversation conversation = getSelectedConversation();
 484		final Account account = conversation.getAccount();
 485		final OnPresenceSelected callback = new OnPresenceSelected() {
 486
 487			@Override
 488			public void onPresenceSelected() {
 489				Intent intent = new Intent();
 490				boolean chooser = false;
 491				String fallbackPackageId = null;
 492				switch (attachmentChoice) {
 493					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 494						intent.setAction(Intent.ACTION_GET_CONTENT);
 495						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 496							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 497						}
 498						intent.setType("image/*");
 499						chooser = true;
 500						break;
 501					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 502						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 503						intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 504						intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 505						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 506						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 507						mPendingImageUris.clear();
 508						mPendingImageUris.add(uri);
 509						break;
 510					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 511						chooser = true;
 512						intent.setType("*/*");
 513						intent.addCategory(Intent.CATEGORY_OPENABLE);
 514						intent.setAction(Intent.ACTION_GET_CONTENT);
 515						break;
 516					case ATTACHMENT_CHOICE_RECORD_VOICE:
 517						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 518						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 519						break;
 520					case ATTACHMENT_CHOICE_LOCATION:
 521						intent.setAction("eu.siacs.conversations.location.request");
 522						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 523						break;
 524				}
 525				if (intent.resolveActivity(getPackageManager()) != null) {
 526					if (chooser) {
 527						startActivityForResult(
 528								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 529								attachmentChoice);
 530					} else {
 531						startActivityForResult(intent, attachmentChoice);
 532					}
 533				} else if (fallbackPackageId != null) {
 534					startActivity(getInstallApkIntent(fallbackPackageId));
 535				}
 536			}
 537		};
 538		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 539			conversation.setNextCounterpart(null);
 540			callback.onPresenceSelected();
 541		} else {
 542			selectPresence(conversation, callback);
 543		}
 544	}
 545
 546	private Intent getInstallApkIntent(final String packageId) {
 547		Intent intent = new Intent(Intent.ACTION_VIEW);
 548		intent.setData(Uri.parse("market://details?id=" + packageId));
 549		if (intent.resolveActivity(getPackageManager()) != null) {
 550			return intent;
 551		} else {
 552			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 553			return intent;
 554		}
 555	}
 556
 557	public void attachFile(final int attachmentChoice) {
 558		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 559			if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(attachmentChoice)) {
 560				return;
 561			}
 562		}
 563		switch (attachmentChoice) {
 564			case ATTACHMENT_CHOICE_LOCATION:
 565				getPreferences().edit().putString("recently_used_quick_action", "location").apply();
 566				break;
 567			case ATTACHMENT_CHOICE_RECORD_VOICE:
 568				getPreferences().edit().putString("recently_used_quick_action", "voice").apply();
 569				break;
 570			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 571				getPreferences().edit().putString("recently_used_quick_action", "photo").apply();
 572				break;
 573			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 574				getPreferences().edit().putString("recently_used_quick_action", "picture").apply();
 575				break;
 576		}
 577		final Conversation conversation = getSelectedConversation();
 578		final int encryption = conversation.getNextEncryption();
 579		final int mode = conversation.getMode();
 580		if (encryption == Message.ENCRYPTION_PGP) {
 581			if (hasPgp()) {
 582				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 583					xmppConnectionService.getPgpEngine().hasKey(
 584							conversation.getContact(),
 585							new UiCallback<Contact>() {
 586
 587								@Override
 588								public void userInputRequried(PendingIntent pi, Contact contact) {
 589									ConversationActivity.this.runIntent(pi, attachmentChoice);
 590								}
 591
 592								@Override
 593								public void success(Contact contact) {
 594									selectPresenceToAttachFile(attachmentChoice, encryption);
 595								}
 596
 597								@Override
 598								public void error(int error, Contact contact) {
 599									replaceToast(getString(error));
 600								}
 601							});
 602				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 603					if (!conversation.getMucOptions().everybodyHasKeys()) {
 604						Toast warning = Toast
 605								.makeText(this,
 606										R.string.missing_public_keys,
 607										Toast.LENGTH_LONG);
 608						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 609						warning.show();
 610					}
 611					selectPresenceToAttachFile(attachmentChoice, encryption);
 612				} else {
 613					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 614							.findFragmentByTag("conversation");
 615					if (fragment != null) {
 616						fragment.showNoPGPKeyDialog(false,
 617								new OnClickListener() {
 618
 619									@Override
 620									public void onClick(DialogInterface dialog,
 621														int which) {
 622										conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 623										xmppConnectionService.updateConversation(conversation);
 624										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 625									}
 626								});
 627					}
 628				}
 629			} else {
 630				showInstallPgpDialog();
 631			}
 632		} else {
 633			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 634				selectPresenceToAttachFile(attachmentChoice, encryption);
 635			}
 636		}
 637	}
 638
 639	@Override
 640	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 641		if (grantResults.length > 0)
 642			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 643				if (requestCode == REQUEST_START_DOWNLOAD) {
 644					if (this.mPendingDownloadableMessage != null) {
 645						startDownloadable(this.mPendingDownloadableMessage);
 646					}
 647				} else {
 648					attachFile(requestCode);
 649				}
 650			} else {
 651				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 652			}
 653	}
 654
 655	public void startDownloadable(Message message) {
 656		if (!Config.ONLY_INTERNAL_STORAGE && !hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 657			this.mPendingDownloadableMessage = message;
 658			return;
 659		}
 660		Transferable transferable = message.getTransferable();
 661		if (transferable != null) {
 662			if (!transferable.start()) {
 663				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 664			}
 665		} else if (message.treatAsDownloadable()) {
 666			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 667		}
 668	}
 669
 670	@Override
 671	public boolean onOptionsItemSelected(final MenuItem item) {
 672		if (item.getItemId() == android.R.id.home) {
 673			showConversationsOverview();
 674			return true;
 675		} else if (item.getItemId() == R.id.action_add) {
 676			startActivity(new Intent(this, StartConversationActivity.class));
 677			return true;
 678		} else if (getSelectedConversation() != null) {
 679			switch (item.getItemId()) {
 680				case R.id.action_attach_file:
 681					attachFileDialog();
 682					break;
 683				case R.id.action_archive:
 684					this.endConversation(getSelectedConversation());
 685					break;
 686				case R.id.action_contact_details:
 687					switchToContactDetails(getSelectedConversation().getContact());
 688					break;
 689				case R.id.action_muc_details:
 690					Intent intent = new Intent(this,
 691							ConferenceDetailsActivity.class);
 692					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 693					intent.putExtra("uuid", getSelectedConversation().getUuid());
 694					startActivity(intent);
 695					break;
 696				case R.id.action_invite:
 697					inviteToConversation(getSelectedConversation());
 698					break;
 699				case R.id.action_security:
 700					selectEncryptionDialog(getSelectedConversation());
 701					break;
 702				case R.id.action_clear_history:
 703					clearHistoryDialog(getSelectedConversation());
 704					break;
 705				case R.id.action_mute:
 706					muteConversationDialog(getSelectedConversation());
 707					break;
 708				case R.id.action_unmute:
 709					unmuteConversation(getSelectedConversation());
 710					break;
 711				case R.id.action_block:
 712					BlockContactDialog.show(this, getSelectedConversation());
 713					break;
 714				case R.id.action_unblock:
 715					BlockContactDialog.show(this, getSelectedConversation());
 716					break;
 717				default:
 718					break;
 719			}
 720			return super.onOptionsItemSelected(item);
 721		} else {
 722			return super.onOptionsItemSelected(item);
 723		}
 724	}
 725
 726	public void endConversation(Conversation conversation) {
 727		endConversation(conversation, true, true);
 728	}
 729
 730	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 731		if (showOverview) {
 732			showConversationsOverview();
 733		}
 734		xmppConnectionService.archiveConversation(conversation);
 735		if (reinit) {
 736			if (conversationList.size() > 0) {
 737				setSelectedConversation(conversationList.get(0));
 738				this.mConversationFragment.reInit(getSelectedConversation());
 739			} else {
 740				setSelectedConversation(null);
 741				if (mRedirected.compareAndSet(false, true)) {
 742					Intent intent = new Intent(this, StartConversationActivity.class);
 743					intent.putExtra("init", true);
 744					startActivity(intent);
 745					finish();
 746				}
 747			}
 748		}
 749	}
 750
 751	@SuppressLint("InflateParams")
 752	protected void clearHistoryDialog(final Conversation conversation) {
 753		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 754		builder.setTitle(getString(R.string.clear_conversation_history));
 755		View dialogView = getLayoutInflater().inflate(
 756				R.layout.dialog_clear_history, null);
 757		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 758				.findViewById(R.id.end_conversation_checkbox);
 759		builder.setView(dialogView);
 760		builder.setNegativeButton(getString(R.string.cancel), null);
 761		builder.setPositiveButton(getString(R.string.delete_messages),
 762				new OnClickListener() {
 763
 764					@Override
 765					public void onClick(DialogInterface dialog, int which) {
 766						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 767						if (endConversationCheckBox.isChecked()) {
 768							endConversation(conversation);
 769						} else {
 770							updateConversationList();
 771							ConversationActivity.this.mConversationFragment.updateMessages();
 772						}
 773					}
 774				});
 775		builder.create().show();
 776	}
 777
 778	protected void attachFileDialog() {
 779		View menuAttachFile = findViewById(R.id.action_attach_file);
 780		if (menuAttachFile == null) {
 781			return;
 782		}
 783		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 784		attachFilePopup.inflate(R.menu.attachment_choices);
 785		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 786			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 787		}
 788		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 789			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 790		}
 791		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 792
 793			@Override
 794			public boolean onMenuItemClick(MenuItem item) {
 795				switch (item.getItemId()) {
 796					case R.id.attach_choose_picture:
 797						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 798						break;
 799					case R.id.attach_take_picture:
 800						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 801						break;
 802					case R.id.attach_choose_file:
 803						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 804						break;
 805					case R.id.attach_record_voice:
 806						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 807						break;
 808					case R.id.attach_location:
 809						attachFile(ATTACHMENT_CHOICE_LOCATION);
 810						break;
 811				}
 812				return false;
 813			}
 814		});
 815		UIHelper.showIconsInPopup(attachFilePopup);
 816		attachFilePopup.show();
 817	}
 818
 819	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 820		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 821			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 822			return;
 823		}
 824		if (view == null) {
 825			return;
 826		}
 827		PopupMenu popup = new PopupMenu(this, view);
 828		popup.inflate(R.menu.verification_choices);
 829		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 830			@Override
 831			public boolean onMenuItemClick(MenuItem menuItem) {
 832				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 833				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 834				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 835				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 836				switch (menuItem.getItemId()) {
 837					case R.id.scan_fingerprint:
 838						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 839						break;
 840					case R.id.ask_question:
 841						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 842						break;
 843					case R.id.manual_verification:
 844						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 845						break;
 846				}
 847				startActivity(intent);
 848				return true;
 849			}
 850		});
 851		popup.show();
 852	}
 853
 854	protected void selectEncryptionDialog(final Conversation conversation) {
 855		View menuItemView = findViewById(R.id.action_security);
 856		if (menuItemView == null) {
 857			return;
 858		}
 859		PopupMenu popup = new PopupMenu(this, menuItemView);
 860		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 861				.findFragmentByTag("conversation");
 862		if (fragment != null) {
 863			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 864
 865				@Override
 866				public boolean onMenuItemClick(MenuItem item) {
 867					switch (item.getItemId()) {
 868						case R.id.encryption_choice_none:
 869							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 870							item.setChecked(true);
 871							break;
 872						case R.id.encryption_choice_otr:
 873							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 874							item.setChecked(true);
 875							break;
 876						case R.id.encryption_choice_pgp:
 877							if (hasPgp()) {
 878								if (conversation.getAccount().getPgpSignature() != null) {
 879									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 880									item.setChecked(true);
 881								} else {
 882									announcePgp(conversation.getAccount(), conversation, onOpenPGPKeyPublished);
 883								}
 884							} else {
 885								showInstallPgpDialog();
 886							}
 887							break;
 888						case R.id.encryption_choice_axolotl:
 889							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 890									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 891							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 892							item.setChecked(true);
 893							break;
 894						default:
 895							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 896							break;
 897					}
 898					xmppConnectionService.updateConversation(conversation);
 899					fragment.updateChatMsgHint();
 900					invalidateOptionsMenu();
 901					refreshUi();
 902					return true;
 903				}
 904			});
 905			popup.inflate(R.menu.encryption_choices);
 906			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 907			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 908			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 909			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 910			pgp.setVisible(Config.supportOpenPgp());
 911			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 912			otr.setVisible(Config.supportOtr());
 913			axolotl.setVisible(Config.supportOmemo());
 914			if (conversation.getMode() == Conversation.MODE_MULTI) {
 915				otr.setVisible(false);
 916			}
 917			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 918				axolotl.setEnabled(false);
 919			}
 920			switch (conversation.getNextEncryption()) {
 921				case Message.ENCRYPTION_NONE:
 922					none.setChecked(true);
 923					break;
 924				case Message.ENCRYPTION_OTR:
 925					otr.setChecked(true);
 926					break;
 927				case Message.ENCRYPTION_PGP:
 928					pgp.setChecked(true);
 929					break;
 930				case Message.ENCRYPTION_AXOLOTL:
 931					axolotl.setChecked(true);
 932					break;
 933				default:
 934					none.setChecked(true);
 935					break;
 936			}
 937			popup.show();
 938		}
 939	}
 940
 941	protected void muteConversationDialog(final Conversation conversation) {
 942		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 943		builder.setTitle(R.string.disable_notifications);
 944		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 945		builder.setItems(R.array.mute_options_descriptions,
 946				new OnClickListener() {
 947
 948					@Override
 949					public void onClick(final DialogInterface dialog, final int which) {
 950						final long till;
 951						if (durations[which] == -1) {
 952							till = Long.MAX_VALUE;
 953						} else {
 954							till = System.currentTimeMillis() + (durations[which] * 1000);
 955						}
 956						conversation.setMutedTill(till);
 957						ConversationActivity.this.xmppConnectionService.updateConversation(conversation);
 958						updateConversationList();
 959						ConversationActivity.this.mConversationFragment.updateMessages();
 960						invalidateOptionsMenu();
 961					}
 962				});
 963		builder.create().show();
 964	}
 965
 966	public void unmuteConversation(final Conversation conversation) {
 967		conversation.setMutedTill(0);
 968		this.xmppConnectionService.updateConversation(conversation);
 969		updateConversationList();
 970		ConversationActivity.this.mConversationFragment.updateMessages();
 971		invalidateOptionsMenu();
 972	}
 973
 974	@Override
 975	public void onBackPressed() {
 976		if (!isConversationsOverviewVisable()) {
 977			showConversationsOverview();
 978		} else {
 979			super.onBackPressed();
 980		}
 981	}
 982
 983	@Override
 984	public boolean onKeyUp(int key, KeyEvent event) {
 985		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 986		final int upKey;
 987		final int downKey;
 988		switch (rotation) {
 989			case Surface.ROTATION_90:
 990				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 991				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 992				break;
 993			case Surface.ROTATION_180:
 994				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 995				downKey = KeyEvent.KEYCODE_DPAD_UP;
 996				break;
 997			case Surface.ROTATION_270:
 998				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 999				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
1000				break;
1001			case Surface.ROTATION_0:
1002			default:
1003				upKey = KeyEvent.KEYCODE_DPAD_UP;
1004				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
1005		}
1006		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
1007		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1008			toggleConversationsOverview();
1009			return true;
1010		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1011			startActivity(new Intent(this, StartConversationActivity.class));
1012			return true;
1013		} else if (modifier && key == downKey) {
1014			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1015				showConversationsOverview();
1016				;
1017			}
1018			return selectDownConversation();
1019		} else if (modifier && key == upKey) {
1020			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1021				showConversationsOverview();
1022			}
1023			return selectUpConversation();
1024		} else if (modifier && key == KeyEvent.KEYCODE_1) {
1025			return openConversationByIndex(0);
1026		} else if (modifier && key == KeyEvent.KEYCODE_2) {
1027			return openConversationByIndex(1);
1028		} else if (modifier && key == KeyEvent.KEYCODE_3) {
1029			return openConversationByIndex(2);
1030		} else if (modifier && key == KeyEvent.KEYCODE_4) {
1031			return openConversationByIndex(3);
1032		} else if (modifier && key == KeyEvent.KEYCODE_5) {
1033			return openConversationByIndex(4);
1034		} else if (modifier && key == KeyEvent.KEYCODE_6) {
1035			return openConversationByIndex(5);
1036		} else if (modifier && key == KeyEvent.KEYCODE_7) {
1037			return openConversationByIndex(6);
1038		} else if (modifier && key == KeyEvent.KEYCODE_8) {
1039			return openConversationByIndex(7);
1040		} else if (modifier && key == KeyEvent.KEYCODE_9) {
1041			return openConversationByIndex(8);
1042		} else if (modifier && key == KeyEvent.KEYCODE_0) {
1043			return openConversationByIndex(9);
1044		} else {
1045			return super.onKeyUp(key, event);
1046		}
1047	}
1048
1049	private void toggleConversationsOverview() {
1050		if (isConversationsOverviewVisable()) {
1051			hideConversationsOverview();
1052			if (mConversationFragment != null) {
1053				mConversationFragment.setFocusOnInputField();
1054			}
1055		} else {
1056			showConversationsOverview();
1057		}
1058	}
1059
1060	private boolean selectUpConversation() {
1061		if (this.mSelectedConversation != null) {
1062			int index = this.conversationList.indexOf(this.mSelectedConversation);
1063			if (index > 0) {
1064				return openConversationByIndex(index - 1);
1065			}
1066		}
1067		return false;
1068	}
1069
1070	private boolean selectDownConversation() {
1071		if (this.mSelectedConversation != null) {
1072			int index = this.conversationList.indexOf(this.mSelectedConversation);
1073			if (index != -1 && index < this.conversationList.size() - 1) {
1074				return openConversationByIndex(index + 1);
1075			}
1076		}
1077		return false;
1078	}
1079
1080	private boolean openConversationByIndex(int index) {
1081		try {
1082			this.conversationWasSelectedByKeyboard = true;
1083			setSelectedConversation(this.conversationList.get(index));
1084			this.mConversationFragment.reInit(getSelectedConversation());
1085			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1086				this.listView.setSelection(index);
1087			}
1088			openConversation();
1089			return true;
1090		} catch (IndexOutOfBoundsException e) {
1091			return false;
1092		}
1093	}
1094
1095	@Override
1096	protected void onNewIntent(final Intent intent) {
1097		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1098			mOpenConversation = null;
1099			mUnprocessedNewIntent = true;
1100			if (xmppConnectionServiceBound) {
1101				handleViewConversationIntent(intent);
1102				intent.setAction(Intent.ACTION_MAIN);
1103			} else {
1104				setIntent(intent);
1105			}
1106		}
1107	}
1108
1109	@Override
1110	public void onStart() {
1111		super.onStart();
1112		this.mRedirected.set(false);
1113		if (this.xmppConnectionServiceBound) {
1114			this.onBackendConnected();
1115		}
1116		if (conversationList.size() >= 1) {
1117			this.onConversationUpdate();
1118		}
1119	}
1120
1121	@Override
1122	public void onPause() {
1123		listView.discardUndo();
1124		super.onPause();
1125		this.mActivityPaused = true;
1126	}
1127
1128	@Override
1129	public void onResume() {
1130		super.onResume();
1131		final int theme = findTheme();
1132		final boolean usingEnterKey = usingEnterKey();
1133		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1134			recreate();
1135		}
1136		this.mActivityPaused = false;
1137
1138
1139		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1140			sendReadMarkerIfNecessary(getSelectedConversation());
1141		}
1142
1143	}
1144
1145	@Override
1146	public void onSaveInstanceState(final Bundle savedInstanceState) {
1147		Conversation conversation = getSelectedConversation();
1148		if (conversation != null) {
1149			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1150			Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1151			if (scrollPosition != null) {
1152				savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1153				savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1154			}
1155		} else {
1156			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1157		}
1158		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1159		if (this.mPendingImageUris.size() >= 1) {
1160			Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1161			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1162		} else {
1163			savedInstanceState.remove(STATE_PENDING_URI);
1164		}
1165		super.onSaveInstanceState(savedInstanceState);
1166	}
1167
1168	private void clearPending() {
1169		mPendingImageUris.clear();
1170		mPendingFileUris.clear();
1171		mPendingGeoUri = null;
1172		mPostponedActivityResult = null;
1173	}
1174
1175	private void redirectToStartConversationActivity() {
1176		Account pendingAccount = xmppConnectionService.getPendingAccount();
1177		if (pendingAccount == null) {
1178			Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1179			startConversationActivity.putExtra("init", true);
1180			startActivity(startConversationActivity);
1181		} else {
1182			switchToAccount(pendingAccount, true);
1183		}
1184		finish();
1185	}
1186
1187	@Override
1188	void onBackendConnected() {
1189		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1190		updateConversationList();
1191
1192		if (mPendingConferenceInvite != null) {
1193			if (mPendingConferenceInvite.execute(this)) {
1194				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1195				mToast.show();
1196			}
1197			mPendingConferenceInvite = null;
1198		}
1199
1200		final Intent intent = getIntent();
1201
1202		if (xmppConnectionService.getAccounts().size() == 0) {
1203			if (mRedirected.compareAndSet(false, true)) {
1204				if (Config.X509_VERIFICATION) {
1205					startActivity(new Intent(this, ManageAccountActivity.class));
1206				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1207					startActivity(new Intent(this, WelcomeActivity.class));
1208				} else {
1209					Intent editAccount = new Intent(this, EditAccountActivity.class);
1210					editAccount.putExtra("init",true);
1211					startActivity(editAccount);
1212				}
1213				finish();
1214			}
1215		} else if (conversationList.size() <= 0) {
1216			if (mRedirected.compareAndSet(false, true)) {
1217				redirectToStartConversationActivity();
1218			}
1219		} else if (selectConversationByUuid(mOpenConversation)) {
1220			if (mPanelOpen) {
1221				showConversationsOverview();
1222			} else {
1223				if (isConversationsOverviewHideable()) {
1224					openConversation();
1225					updateActionBarTitle(true);
1226				}
1227			}
1228			if (this.mConversationFragment.reInit(getSelectedConversation())) {
1229				Log.d(Config.LOGTAG,"setting scroll position on fragment");
1230				this.mConversationFragment.setScrollPosition(mScrollPosition);
1231			}
1232			mOpenConversation = null;
1233		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1234			clearPending();
1235			handleViewConversationIntent(intent);
1236			intent.setAction(Intent.ACTION_MAIN);
1237		} else if (getSelectedConversation() == null) {
1238			reInitLatestConversation();
1239		} else {
1240			this.mConversationFragment.messageListAdapter.updatePreferences();
1241			this.mConversationFragment.messagesView.invalidateViews();
1242			this.mConversationFragment.setupIme();
1243		}
1244
1245		if (this.mPostponedActivityResult != null) {
1246			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1247		}
1248
1249		final boolean stopping = isStopping();
1250
1251		if (!forbidProcessingPendings) {
1252			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1253				Uri foo = i.next();
1254				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1255				attachImageToConversation(getSelectedConversation(), foo);
1256			}
1257
1258			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1259				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1260				attachFileToConversation(getSelectedConversation(), i.next());
1261			}
1262
1263			if (mPendingGeoUri != null) {
1264				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1265				mPendingGeoUri = null;
1266			}
1267		}
1268		forbidProcessingPendings = false;
1269
1270		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService) && !mRedirected.get()) {
1271			openBatteryOptimizationDialogIfNeeded();
1272		}
1273		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
1274			xmppConnectionService.getNotificationService().setOpenConversation(null);
1275		} else {
1276			xmppConnectionService.getNotificationService().setOpenConversation(getSelectedConversation());
1277		}
1278	}
1279
1280	private boolean isStopping() {
1281		if (Build.VERSION.SDK_INT >= 17) {
1282			return isFinishing() || isDestroyed();
1283		} else {
1284			return isFinishing();
1285		}
1286	}
1287
1288	private void reInitLatestConversation() {
1289		showConversationsOverview();
1290		clearPending();
1291		setSelectedConversation(conversationList.get(0));
1292		this.mConversationFragment.reInit(getSelectedConversation());
1293	}
1294
1295	private void handleViewConversationIntent(final Intent intent) {
1296		final String uuid = intent.getStringExtra(CONVERSATION);
1297		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1298		final String text = intent.getStringExtra(TEXT);
1299		final String nick = intent.getStringExtra(NICK);
1300		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1301		if (selectConversationByUuid(uuid)) {
1302			this.mConversationFragment.reInit(getSelectedConversation());
1303			if (nick != null) {
1304				if (pm) {
1305					Jid jid = getSelectedConversation().getJid();
1306					try {
1307						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1308						this.mConversationFragment.privateMessageWith(next);
1309					} catch (final InvalidJidException ignored) {
1310						//do nothing
1311					}
1312				} else {
1313					this.mConversationFragment.highlightInConference(nick);
1314				}
1315			} else {
1316				this.mConversationFragment.appendText(text);
1317			}
1318			hideConversationsOverview();
1319			mUnprocessedNewIntent = false;
1320			openConversation();
1321			if (mContentView instanceof SlidingPaneLayout) {
1322				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1323			}
1324			if (downloadUuid != null) {
1325				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1326				if (message != null) {
1327					startDownloadable(message);
1328				}
1329			}
1330		} else {
1331			mUnprocessedNewIntent = false;
1332		}
1333	}
1334
1335	private boolean selectConversationByUuid(String uuid) {
1336		if (uuid == null) {
1337			return false;
1338		}
1339		for (Conversation aConversationList : conversationList) {
1340			if (aConversationList.getUuid().equals(uuid)) {
1341				setSelectedConversation(aConversationList);
1342				return true;
1343			}
1344		}
1345		return false;
1346	}
1347
1348	@Override
1349	protected void unregisterListeners() {
1350		super.unregisterListeners();
1351		xmppConnectionService.getNotificationService().setOpenConversation(null);
1352	}
1353
1354	@SuppressLint("NewApi")
1355	private static List<Uri> extractUriFromIntent(final Intent intent) {
1356		List<Uri> uris = new ArrayList<>();
1357		if (intent == null) {
1358			return uris;
1359		}
1360		Uri uri = intent.getData();
1361		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1362			final ClipData clipData = intent.getClipData();
1363			if (clipData != null) {
1364				for (int i = 0; i < clipData.getItemCount(); ++i) {
1365					uris.add(clipData.getItemAt(i).getUri());
1366				}
1367			}
1368		} else {
1369			uris.add(uri);
1370		}
1371		return uris;
1372	}
1373
1374	@Override
1375	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1376		super.onActivityResult(requestCode, resultCode, data);
1377		if (resultCode == RESULT_OK) {
1378			if (requestCode == REQUEST_DECRYPT_PGP) {
1379				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1380			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1381				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1382				if (xmppConnectionServiceBound) {
1383					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1384						// associate selected PGP keyId with the account
1385						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1386						// we need to announce the key as described in XEP-027
1387						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1388					} else {
1389						choosePgpSignId(mSelectedConversation.getAccount());
1390					}
1391					this.mPostponedActivityResult = null;
1392				} else {
1393					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1394				}
1395			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1396				if (xmppConnectionServiceBound) {
1397					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1398					this.mPostponedActivityResult = null;
1399				} else {
1400					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1401				}
1402			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1403				mPendingImageUris.clear();
1404				mPendingImageUris.addAll(extractUriFromIntent(data));
1405				if (xmppConnectionServiceBound) {
1406					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1407						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1408						attachImageToConversation(getSelectedConversation(), i.next());
1409					}
1410				}
1411			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1412				final List<Uri> uris = extractUriFromIntent(data);
1413				final Conversation c = getSelectedConversation();
1414				final OnPresenceSelected callback = new OnPresenceSelected() {
1415					@Override
1416					public void onPresenceSelected() {
1417						mPendingFileUris.clear();
1418						mPendingFileUris.addAll(uris);
1419						if (xmppConnectionServiceBound) {
1420							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1421								Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1422								attachFileToConversation(c, i.next());
1423							}
1424						}
1425					}
1426				};
1427				if (c == null || c.getMode() == Conversation.MODE_MULTI
1428						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1429						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1430					callback.onPresenceSelected();
1431				} else {
1432					selectPresence(c, callback);
1433				}
1434			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1435				if (mPendingImageUris.size() == 1) {
1436					Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1437					mPendingImageUris.set(0, uri);
1438					if (xmppConnectionServiceBound) {
1439						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1440						attachImageToConversation(getSelectedConversation(), uri);
1441						mPendingImageUris.clear();
1442					}
1443					if (!Config.ONLY_INTERNAL_STORAGE) {
1444						Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1445						intent.setData(uri);
1446						sendBroadcast(intent);
1447					}
1448				} else {
1449					mPendingImageUris.clear();
1450				}
1451			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1452				double latitude = data.getDoubleExtra("latitude", 0);
1453				double longitude = data.getDoubleExtra("longitude", 0);
1454				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1455				if (xmppConnectionServiceBound) {
1456					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1457					this.mPendingGeoUri = null;
1458				}
1459			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1460				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1461				if (xmppConnectionServiceBound) {
1462					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1463					this.mPostponedActivityResult = null;
1464				} else {
1465					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1466				}
1467
1468			}
1469		} else {
1470			mPendingImageUris.clear();
1471			mPendingFileUris.clear();
1472			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1473				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1474			}
1475			if (requestCode == REQUEST_BATTERY_OP) {
1476				setNeverAskForBatteryOptimizationsAgain();
1477			}
1478		}
1479	}
1480
1481	private long getMaxHttpUploadSize(Conversation conversation) {
1482		final XmppConnection connection = conversation.getAccount().getXmppConnection();
1483		return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1484	}
1485
1486	private void setNeverAskForBatteryOptimizationsAgain() {
1487		getPreferences().edit().putBoolean("show_battery_optimization", false).apply();
1488	}
1489
1490	private void openBatteryOptimizationDialogIfNeeded() {
1491		if (hasAccountWithoutPush()
1492				&& isOptimizingBattery()
1493				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1494			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1495			builder.setTitle(R.string.battery_optimizations_enabled);
1496			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1497			builder.setPositiveButton(R.string.next, new OnClickListener() {
1498				@Override
1499				public void onClick(DialogInterface dialog, int which) {
1500					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1501					Uri uri = Uri.parse("package:" + getPackageName());
1502					intent.setData(uri);
1503					try {
1504						startActivityForResult(intent, REQUEST_BATTERY_OP);
1505					} catch (ActivityNotFoundException e) {
1506						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1507					}
1508				}
1509			});
1510			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1511				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1512					@Override
1513					public void onDismiss(DialogInterface dialog) {
1514						setNeverAskForBatteryOptimizationsAgain();
1515					}
1516				});
1517			}
1518			AlertDialog dialog = builder.create();
1519			dialog.setCanceledOnTouchOutside(false);
1520			dialog.show();
1521		}
1522	}
1523
1524	private boolean hasAccountWithoutPush() {
1525		for(Account account : xmppConnectionService.getAccounts()) {
1526			if (account.getStatus() != Account.State.DISABLED
1527					&& !xmppConnectionService.getPushManagementService().availableAndUseful(account)) {
1528				return true;
1529			}
1530		}
1531		return false;
1532	}
1533
1534	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1535		if (conversation == null) {
1536			return;
1537		}
1538		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1539
1540			@Override
1541			public void success(Message message) {
1542				xmppConnectionService.sendMessage(message);
1543			}
1544
1545			@Override
1546			public void error(int errorCode, Message object) {
1547
1548			}
1549
1550			@Override
1551			public void userInputRequried(PendingIntent pi, Message object) {
1552
1553			}
1554		});
1555	}
1556
1557	private void attachFileToConversation(Conversation conversation, Uri uri) {
1558		if (conversation == null) {
1559			return;
1560		}
1561		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1562		prepareFileToast.show();
1563		xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
1564			@Override
1565			public void inform(final String text) {
1566				hidePrepareFileToast(prepareFileToast);
1567				runOnUiThread(new Runnable() {
1568					@Override
1569					public void run() {
1570						replaceToast(text);
1571					}
1572				});
1573			}
1574
1575			@Override
1576			public void success(Message message) {
1577				runOnUiThread(new Runnable() {
1578					@Override
1579					public void run() {
1580						hideToast();
1581					}
1582				});
1583				hidePrepareFileToast(prepareFileToast);
1584				xmppConnectionService.sendMessage(message);
1585			}
1586
1587			@Override
1588			public void error(final int errorCode, Message message) {
1589				hidePrepareFileToast(prepareFileToast);
1590				runOnUiThread(new Runnable() {
1591					@Override
1592					public void run() {
1593						replaceToast(getString(errorCode));
1594					}
1595				});
1596
1597			}
1598
1599			@Override
1600			public void userInputRequried(PendingIntent pi, Message message) {
1601				hidePrepareFileToast(prepareFileToast);
1602			}
1603		});
1604	}
1605
1606	public void attachImageToConversation(Uri uri) {
1607		this.attachImageToConversation(getSelectedConversation(), uri);
1608	}
1609
1610	private void attachImageToConversation(Conversation conversation, Uri uri) {
1611		if (conversation == null) {
1612			return;
1613		}
1614		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1615		prepareFileToast.show();
1616		xmppConnectionService.attachImageToConversation(conversation, uri,
1617				new UiCallback<Message>() {
1618
1619					@Override
1620					public void userInputRequried(PendingIntent pi, Message object) {
1621						hidePrepareFileToast(prepareFileToast);
1622					}
1623
1624					@Override
1625					public void success(Message message) {
1626						hidePrepareFileToast(prepareFileToast);
1627						xmppConnectionService.sendMessage(message);
1628					}
1629
1630					@Override
1631					public void error(final int error, Message message) {
1632						hidePrepareFileToast(prepareFileToast);
1633						runOnUiThread(new Runnable() {
1634							@Override
1635							public void run() {
1636								replaceToast(getString(error));
1637							}
1638						});
1639					}
1640				});
1641	}
1642
1643	private void hidePrepareFileToast(final Toast prepareFileToast) {
1644		if (prepareFileToast != null) {
1645			runOnUiThread(new Runnable() {
1646
1647				@Override
1648				public void run() {
1649					prepareFileToast.cancel();
1650				}
1651			});
1652		}
1653	}
1654
1655	public void updateConversationList() {
1656		xmppConnectionService.populateWithOrderedConversations(conversationList);
1657		if (!conversationList.contains(mSelectedConversation)) {
1658			mSelectedConversation = null;
1659		}
1660		if (swipedConversation != null) {
1661			if (swipedConversation.isRead()) {
1662				conversationList.remove(swipedConversation);
1663			} else {
1664				listView.discardUndo();
1665			}
1666		}
1667		listAdapter.notifyDataSetChanged();
1668	}
1669
1670	public void runIntent(PendingIntent pi, int requestCode) {
1671		try {
1672			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1673					null, 0, 0, 0);
1674		} catch (final SendIntentException ignored) {
1675		}
1676	}
1677
1678	public void encryptTextMessage(Message message) {
1679		xmppConnectionService.getPgpEngine().encrypt(message,
1680				new UiCallback<Message>() {
1681
1682					@Override
1683					public void userInputRequried(PendingIntent pi,Message message) {
1684						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1685					}
1686
1687					@Override
1688					public void success(Message message) {
1689						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1690						xmppConnectionService.sendMessage(message);
1691						runOnUiThread(new Runnable() {
1692							@Override
1693							public void run() {
1694								mConversationFragment.messageSent();
1695							}
1696						});
1697					}
1698
1699					@Override
1700					public void error(final int error, Message message) {
1701						runOnUiThread(new Runnable() {
1702							@Override
1703							public void run() {
1704								mConversationFragment.doneSendingPgpMessage();
1705								Toast.makeText(ConversationActivity.this,
1706										R.string.unable_to_connect_to_keychain,
1707										Toast.LENGTH_SHORT
1708								).show();
1709							}
1710						});
1711
1712					}
1713				});
1714	}
1715
1716	public boolean useSendButtonToIndicateStatus() {
1717		return getPreferences().getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status));
1718	}
1719
1720	public boolean indicateReceived() {
1721		return getPreferences().getBoolean("indicate_received", getResources().getBoolean(R.bool.indicate_received));
1722	}
1723
1724	public boolean useGreenBackground() {
1725		return getPreferences().getBoolean("use_green_background",getResources().getBoolean(R.bool.use_green_background));
1726	}
1727
1728	protected boolean trustKeysIfNeeded(int requestCode) {
1729		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1730	}
1731
1732	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1733		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1734		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1735		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1736		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1737		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1738		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1739		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1740		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1741			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1742			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1743			String[] contacts = new String[targets.size()];
1744			for(int i = 0; i < contacts.length; ++i) {
1745				contacts[i] = targets.get(i).toString();
1746			}
1747			intent.putExtra("contacts", contacts);
1748			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1749			intent.putExtra("choice", attachmentChoice);
1750			intent.putExtra("conversation",mSelectedConversation.getUuid());
1751			startActivityForResult(intent, requestCode);
1752			return true;
1753		} else {
1754			return false;
1755		}
1756	}
1757
1758	@Override
1759	protected void refreshUiReal() {
1760		updateConversationList();
1761		if (conversationList.size() > 0) {
1762			if (!this.mConversationFragment.isAdded()) {
1763				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1764			}
1765			if (getSelectedConversation() == null) {
1766				reInitLatestConversation();
1767			} else {
1768				ConversationActivity.this.mConversationFragment.updateMessages();
1769				updateActionBarTitle();
1770				invalidateOptionsMenu();
1771			}
1772		} else {
1773			if (!isStopping() && mRedirected.compareAndSet(false, true)) {
1774				redirectToStartConversationActivity();
1775			}
1776			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1777		}
1778	}
1779
1780	@Override
1781	public void onAccountUpdate() {
1782		this.refreshUi();
1783	}
1784
1785	@Override
1786	public void onConversationUpdate() {
1787		this.refreshUi();
1788	}
1789
1790	@Override
1791	public void onRosterUpdate() {
1792		this.refreshUi();
1793	}
1794
1795	@Override
1796	public void OnUpdateBlocklist(Status status) {
1797		this.refreshUi();
1798	}
1799
1800	public void unblockConversation(final Blockable conversation) {
1801		xmppConnectionService.sendUnblockRequest(conversation);
1802	}
1803
1804	public boolean enterIsSend() {
1805		return getPreferences().getBoolean("enter_is_send",getResources().getBoolean(R.bool.enter_is_send));
1806	}
1807
1808	@Override
1809	public void onShowErrorToast(final int resId) {
1810		runOnUiThread(new Runnable() {
1811			@Override
1812			public void run() {
1813				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1814			}
1815		});
1816	}
1817
1818	public boolean highlightSelectedConversations() {
1819		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1820	}
1821}