List of usage examples for android.content Intent getParcelableExtra
public <T extends Parcelable> T getParcelableExtra(String name)
From source file:com.android.mail.compose.ComposeActivity.java
/** * Fill all the widgets with the content found in the Intent Extra, if any. * Also apply the same style to all widgets. Note: if initFromExtras is * called as a result of switching between reply, reply all, and forward per * the latest revision of Gmail, and the user has already made changes to * attachments on a previous incarnation of the message (as a reply, reply * all, or forward), the original attachments from the message will not be * re-instantiated. The user's changes will be respected. This follows the * web gmail interaction./* ww w . j a v a2 s .co m*/ * @return {@code true} if the activity should not call {@link #finishSetup}. */ public boolean initFromExtras(Intent intent) { // If we were invoked with a SENDTO intent, the value // should take precedence final Uri dataUri = intent.getData(); if (dataUri != null) { if (MAIL_TO.equals(dataUri.getScheme())) { initFromMailTo(dataUri.toString()); } else { if (!mAccount.composeIntentUri.equals(dataUri)) { String toText = dataUri.getSchemeSpecificPart(); if (toText != null) { mTo.setText(""); addToAddresses(Arrays.asList(TextUtils.split(toText, ","))); } } } } String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); if (extraStrings != null) { addToAddresses(Arrays.asList(extraStrings)); } extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC); if (extraStrings != null) { addCcAddresses(Arrays.asList(extraStrings), null); } extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC); if (extraStrings != null) { addBccAddresses(Arrays.asList(extraStrings)); } String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (extraString != null) { mSubject.setText(extraString); } for (String extra : ALL_EXTRAS) { if (intent.hasExtra(extra)) { String value = intent.getStringExtra(extra); if (EXTRA_TO.equals(extra)) { addToAddresses(Arrays.asList(TextUtils.split(value, ","))); } else if (EXTRA_CC.equals(extra)) { addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null); } else if (EXTRA_BCC.equals(extra)) { addBccAddresses(Arrays.asList(TextUtils.split(value, ","))); } else if (EXTRA_SUBJECT.equals(extra)) { mSubject.setText(value); } else if (EXTRA_BODY.equals(extra)) { setBody(value, true /* with signature */); } else if (EXTRA_QUOTED_TEXT.equals(extra)) { initQuotedText(value, true /* shouldQuoteText */); } } } Bundle extras = intent.getExtras(); if (extras != null) { CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT); setBody((text != null) ? text : "", true /* with signature */); // TODO - support EXTRA_HTML_TEXT } mExtraValues = intent.getParcelableExtra(EXTRA_VALUES); if (mExtraValues != null) { LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString()); initExtraValues(mExtraValues); return true; } return false; }
From source file:com.nest5.businessClient.Initialactivity.java
public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); // ////Log.i(TAG, String.valueOf(redeemCoupon)); if (scanResult != null) { }//from w ww . ja v a 2 s .com if (requestCode == RETURN_FROM_DESIGN_TABLE) { String result = null; if (resultCode == RESULT_OK) { result = intent.getStringExtra(Setup.SAVED_TABLES); } if (resultCode == RESULT_CANCELED) { //Write your code if there's no result } if (result != null) { //load tables view and allow to make order for it showMesasLayout(); } } if (requestCode == RETURN_FROM_OPENCLOSE_TABLE) { Table actual = null; int clientes = 0; if (resultCode == RESULT_OK) { actual = intent.getParcelableExtra("MIMESA"); clientes = intent.getIntExtra("MIMESACLIENTES", 0); if (actual != null) { //load tables view and allow to make order for it currentTable = new CurrentTable<Table, Integer>(actual, clientes); statusText.setVisibility(View.VISIBLE); statusText.setText(actual.getName() + " con " + clientes + " Clientes."); //Log.i("MISPRUEBAS",currentTable.getTable().getName()); } } if (resultCode == RESULT_CANCELED) { //Write your code if there's no result } if (resultCode == Setup.CLOSE_TABLE) { //Log.i("MISPRUEBAS","volviendo de cerrar mesa"); actual = intent.getParcelableExtra("MIMESA"); //tomar mesa que se cierra, preguntar si es cancelar venta o pagar, si es cancelar borra de opentables, de orders etc y si es pagar, pone en currentsale y abre dialogo pagar if (actual != null) { //Log.i("MISPRUEBAS","volviendo de cerrar mesa y no esta nulo"); //load tables view and allow to make order for it currentTable = new CurrentTable<Table, Integer>(actual, 0); //Log.i("MISPRUEBAS","regreasa de dar clic en cerrar mesa con: "+currentTable.getTable().getName()); statusText.setVisibility(View.VISIBLE); statusText.setText("Cerrando: " + actual.getName()); openOtherWindow = true; openOtherWindowAction = OPEN_TABLE_ACTION; } } } // else continue with any other code you need in the method SharedPreferences defaultprefs = PreferenceManager.getDefaultSharedPreferences(mContext); boolean layouttables = defaultprefs.getBoolean("arrange_tables", false); MenuItem tablelayouts = mMenu.findItem(R.id.layouttables); MenuItem showtables = mMenu.findItem(R.id.menu_show_tables); boolean change = false; if (tablelayouts.isVisible() != layouttables) change = true; tablelayouts.setVisible(layouttables); showtables.setVisible(layouttables); if (change) { invalidateOptionsMenu(); } }
From source file:com.irccloud.android.activity.MainActivity.java
private void setFromIntent(Intent intent) { launchBid = -1;// ww w . j a v a 2 s .c o m launchURI = null; if (NetworkConnection.getInstance().ready) setIntent(new Intent(this, MainActivity.class)); if (intent.hasExtra("bid")) { int new_bid = intent.getIntExtra("bid", 0); if (NetworkConnection.getInstance().ready && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED && BuffersDataSource.getInstance().getBuffer(new_bid) == null) { Crashlytics.log(Log.WARN, "IRCCloud", "Invalid bid requested by launch intent: " + new_bid); Notifications.getInstance().deleteNotificationsForBid(new_bid); if (excludeBIDTask != null) excludeBIDTask.cancel(true); excludeBIDTask = new ExcludeBIDTask(); excludeBIDTask.execute(new_bid); return; } else if (BuffersDataSource.getInstance().getBuffer(new_bid) != null) { Crashlytics.log(Log.DEBUG, "IRCCloud", "Found BID, switching buffers"); if (buffer != null && buffer.bid != new_bid) backStack.add(0, buffer.bid); buffer = BuffersDataSource.getInstance().getBuffer(new_bid); server = ServersDataSource.getInstance().getServer(buffer.cid); } else { Crashlytics.log(Log.DEBUG, "IRCCloud", "BID not found, will try after reconnecting"); launchBid = new_bid; } } if (intent.getData() != null && intent.getData().getScheme() != null && intent.getData().getScheme().startsWith("irc")) { if (open_uri(intent.getData())) { return; } else { launchURI = intent.getData(); buffer = null; server = null; } } else if (intent.hasExtra("cid")) { if (buffer == null) { buffer = BuffersDataSource.getInstance().getBufferByName(intent.getIntExtra("cid", 0), intent.getStringExtra("name")); if (buffer != null) { server = ServersDataSource.getInstance().getServer(intent.getIntExtra("cid", 0)); } } } if (buffer == null) { server = null; } else { if (intent.hasExtra(Intent.EXTRA_STREAM)) { String type = getContentResolver().getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)); if (type != null && type.startsWith("image/") && (!NetworkConnection.getInstance().uploadsAvailable() || PreferenceManager.getDefaultSharedPreferences(this) .getString("image_service", "IRCCloud").equals("imgur"))) { new ImgurRefreshTask((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)).execute((Void) null); } else { fileUploadTask = new FileUploadTask((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM), this); fileUploadTask.execute((Void) null); } } if (intent.hasExtra(Intent.EXTRA_TEXT)) { if (intent.hasExtra(Intent.EXTRA_SUBJECT)) buffer.draft = intent.getStringExtra(Intent.EXTRA_SUBJECT) + " (" + intent.getStringExtra(Intent.EXTRA_TEXT) + ")"; else buffer.draft = intent.getStringExtra(Intent.EXTRA_TEXT); } } if (buffer == null) { launchBid = intent.getIntExtra("bid", -1); } else { onBufferSelected(buffer.bid); } }
From source file:com.bernard.beaconportal.activities.activity.MessageList.java
private boolean decodeExtras(Intent intent) { String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) { Uri uri = intent.getData();//from w w w. j a v a 2s .c o m List<String> segmentList = uri.getPathSegments(); String accountId = segmentList.get(0); Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts(); for (Account account : accounts) { if (String.valueOf(account.getAccountNumber()).equals(accountId)) { mMessageReference = new MessageReference(); mMessageReference.accountUuid = account.getUuid(); mMessageReference.folderName = segmentList.get(1); mMessageReference.uid = segmentList.get(2); break; } } } else if (ACTION_SHORTCUT.equals(action)) { // Handle shortcut intents String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER); if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) { mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch(); } else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) { mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch(); } } else if (intent.getStringExtra(SearchManager.QUERY) != null) { // check if this intent comes from the system search ( remote ) if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // Query was received from Search Dialog String query = intent.getStringExtra(SearchManager.QUERY); mSearch = new LocalSearch(getString(R.string.search_results)); mSearch.setManualSearch(true); mNoThreading = true; mSearch.or(new SearchCondition(Searchfield.SENDER, Attribute.CONTAINS, query)); mSearch.or(new SearchCondition(Searchfield.SUBJECT, Attribute.CONTAINS, query)); mSearch.or(new SearchCondition(Searchfield.MESSAGE_CONTENTS, Attribute.CONTAINS, query)); Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT)); // searches started from a folder list activity will provide // an account, but no folder if (appData.getString(EXTRA_SEARCH_FOLDER) != null) { mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER)); } } else { mSearch.addAccountUuid(SearchSpecification.ALL_ACCOUNTS); } } } else { // regular LocalSearch object was passed mSearch = intent.getParcelableExtra(EXTRA_SEARCH); mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false); } if (mMessageReference == null) { mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); } if (mMessageReference != null) { mSearch = new LocalSearch(); mSearch.addAccountUuid(mMessageReference.accountUuid); mSearch.addAllowedFolder(mMessageReference.folderName); } if (mSearch == null) { // We've most likely been started by an old unread widget String accountUuid = intent.getStringExtra("account"); String folderName = intent.getStringExtra("folder"); mSearch = new LocalSearch(folderName); mSearch.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid); if (folderName != null) { mSearch.addAllowedFolder(folderName); } } Preferences prefs = Preferences.getPreferences(getApplicationContext()); String[] accountUuids = mSearch.getAccountUuids(); if (mSearch.searchAllAccounts()) { Account[] accounts = prefs.getAccounts(); mSingleAccountMode = (accounts.length == 1); if (mSingleAccountMode) { mAccount = accounts[0]; } } else { mSingleAccountMode = (accountUuids.length == 1); if (mSingleAccountMode) { mAccount = prefs.getAccount(accountUuids[0]); } } mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1); if (mSingleAccountMode && (mAccount == null || !mAccount.isAvailable(this))) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return false; } if (mSingleFolderMode) { mFolderName = mSearch.getFolderNames().get(0); } // now we know if we are in single account mode and need a subtitle mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE); return true; }
From source file:com.android.mms.ui.ComposeMessageActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (LogTag.VERBOSE) { log("onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data); }/*from w ww . j av a2 s . co m*/ mWaitingForSubActivity = false; // We're back! mShouldLoadDraft = false; if (mWorkingMessage.isFakeMmsForDraft()) { // We no longer have to fake the fact we're an Mms. At this point we are or we aren't, // based on attachments and other Mms attrs. mWorkingMessage.removeFakeMmsForDraft(); } if (requestCode == REQUEST_CODE_PICK) { mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation); } if (requestCode == REQUEST_CODE_ADD_CONTACT) { // The user might have added a new contact. When we tell contacts to add a contact // and tap "Done", we're not returned to Messaging. If we back out to return to // messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore, // assume a contact was added and get the contact and force our cached contact to // get reloaded with the new info (such as contact name). After the // contact is reloaded, the function onUpdate() in this file will get called // and it will update the title bar, etc. if (mAddContactIntent != null) { String address = mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL); if (address == null) { address = mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE); } if (address != null) { Contact contact = Contact.get(address, false); if (contact != null) { contact.reload(); } } } } if (resultCode != RESULT_OK) { if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode); return; } switch (requestCode) { case REQUEST_CODE_CREATE_SLIDESHOW: if (data != null) { WorkingMessage newMessage = WorkingMessage.load(this, data.getData()); if (newMessage != null) { // Here we should keep the subject from the old mWorkingMessage. setNewMessageSubject(newMessage); mWorkingMessage = newMessage; mWorkingMessage.setConversation(mConversation); updateThreadIdIfRunning(); drawTopPanel(false); drawBottomPanel(); updateSendButtonState(); } } break; case REQUEST_CODE_TAKE_PICTURE: { // create a file based uri and pass to addImage(). We want to read the JPEG // data directly from file (using UriImage) instead of decoding it into a Bitmap, // which takes up too much memory and could easily lead to OOM. File file = new File(TempFileProvider.getScrapPath(this)); Uri uri = Uri.fromFile(file); // Remove the old captured picture's thumbnail from the cache MmsApp.getApplication().getThumbnailManager().removeThumbnail(uri); addImageAsync(uri, false); break; } case REQUEST_CODE_ATTACH_IMAGE: { if (data != null) { addImageAsync(data.getData(), false); } break; } case REQUEST_CODE_TAKE_VIDEO: Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null, this); // Remove the old captured video's thumbnail from the cache MmsApp.getApplication().getThumbnailManager().removeThumbnail(videoUri); addVideoAsync(videoUri, false); // can handle null videoUri break; case REQUEST_CODE_ATTACH_VIDEO: if (data != null) { addVideoAsync(data.getData(), false); } break; case REQUEST_CODE_ATTACH_SOUND: { // Attempt to add the audio to the attachment. Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (uri == null) { uri = data.getData(); } else if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) { break; } addAudio(uri); break; } case REQUEST_CODE_RECORD_SOUND: if (data != null) { addAudio(data.getData()); } break; case REQUEST_CODE_ECM_EXIT_DIALOG: boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false); if (outOfEmergencyMode) { sendMessage(false); } break; case REQUEST_CODE_PICK: if (data != null) { processPickResult(data); } break; case REQUEST_CODE_ADD_RECIPIENTS: insertNumbersIntoRecipientsEditor(data.getStringArrayListExtra(SelectRecipientsList.EXTRA_RECIPIENTS)); break; default: if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode); break; } }
From source file:com.codename1.impl.android.AndroidImplementation.java
@Override public String getAppArg() { if (super.getAppArg() != null) { // This just maintains backward compatibility in case people are manually // setting the AppArg in their properties. It reproduces the general // behaviour the existed when AppArg was just another Display property. return super.getAppArg(); }//from w w w . j a va 2 s. c o m if (getActivity() == null) { return null; } android.content.Intent intent = getActivity().getIntent(); if (intent != null) { Uri u = intent.getData(); String scheme = intent.getScheme(); if (u == null && intent.getExtras() != null) { if (intent.getExtras().keySet().contains("android.intent.extra.STREAM")) { try { u = (Uri) intent.getParcelableExtra("android.intent.extra.STREAM"); scheme = u.getScheme(); System.out.println("u=" + u); } catch (Exception ex) { Log.d("Codename One", "Failed to load parcelable extra from intent: " + ex.getMessage()); } } } if (u != null) { //String scheme = intent.getScheme(); intent.setData(null); if ("content".equals(scheme)) { try { InputStream attachment = getActivity().getContentResolver().openInputStream(u); if (attachment != null) { String name = getContentName(getActivity().getContentResolver(), u); if (name != null) { String filePath = getAppHomePath() + getFileSystemSeparator() + name; File f = new File(filePath); OutputStream tmp = createFileOuputStream(f); byte[] buffer = new byte[1024]; int read = -1; while ((read = attachment.read(buffer)) > -1) { tmp.write(buffer, 0, read); } tmp.close(); attachment.close(); setAppArg(filePath); return filePath; } } } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } } else { /* // Why do we need this special case? u.toString() // will include the full URL including query string. // This special case causes urls like myscheme://part1/part2 // to only return "/part2" which is obviously problematic and // is inconsistent with iOS. Is this special case necessary // in some versions of Android? String encodedPath = u.getEncodedPath(); if (encodedPath != null && encodedPath.length() > 0) { String query = u.getQuery(); if(query != null && query.length() > 0){ encodedPath += "?" + query; } setAppArg(encodedPath); return encodedPath; } */ setAppArg(u.toString()); return u.toString(); } } } return null; }
From source file:com.keylesspalace.tusky.ComposeActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT); if (theme.equals("black")) { setTheme(R.style.TuskyDialogActivityBlackTheme); }/*from w w w . j a v a 2s .c om*/ setContentView(R.layout.activity_compose); replyTextView = findViewById(R.id.composeReplyView); replyContentTextView = findViewById(R.id.composeReplyContentView); textEditor = findViewById(R.id.composeEditField); mediaPreviewBar = findViewById(R.id.compose_media_preview_bar); contentWarningBar = findViewById(R.id.composeContentWarningBar); contentWarningEditor = findViewById(R.id.composeContentWarningField); charactersLeft = findViewById(R.id.composeCharactersLeftView); tootButton = findViewById(R.id.composeTootButton); pickButton = findViewById(R.id.composeAddMediaButton); visibilityButton = findViewById(R.id.composeToggleVisibilityButton); contentWarningButton = findViewById(R.id.composeContentWarningButton); emojiButton = findViewById(R.id.composeEmojiButton); hideMediaToggle = findViewById(R.id.composeHideMediaButton); emojiView = findViewById(R.id.emojiView); emojiList = Collections.emptyList(); saveTootHelper = new SaveTootHelper(database.tootDao(), this); // Setup the toolbar. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(null); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp); ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint); actionBar.setHomeAsUpIndicator(closeIcon); } // setup the account image final AccountEntity activeAccount = accountManager.getActiveAccount(); if (activeAccount != null) { ImageView composeAvatar = findViewById(R.id.composeAvatar); if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) { composeAvatar.setImageResource(R.drawable.avatar_default); } else { Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default) .placeholder(R.drawable.avatar_default).into(composeAvatar); } composeAvatar.setContentDescription( getString(R.string.compose_active_account_description, activeAccount.getFullName())); mastodonApi.getInstance().enqueue(new Callback<Instance>() { @Override public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) { if (response.isSuccessful() && response.body().getMaxTootChars() != null) { maximumTootCharacters = response.body().getMaxTootChars(); updateVisibleCharactersLeft(); cacheInstanceMetadata(activeAccount); } } @Override public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) { Log.w(TAG, "error loading instance data", t); loadCachedInstanceMetadata(activeAccount); } }); mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() { @Override public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) { emojiList = response.body(); setEmojiList(emojiList); cacheInstanceMetadata(activeAccount); } @Override public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) { Log.w(TAG, "error loading custom emojis", t); loadCachedInstanceMetadata(activeAccount); } }); } else { // do not do anything when not logged in, activity will be finished in super.onCreate() anyway return; } composeOptionsView = findViewById(R.id.composeOptionsBottomSheet); composeOptionsView.setListener(this); composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView); composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet)); emojiBehavior = BottomSheetBehavior.from(emojiView); emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false)); enableButton(emojiButton, false, false); // Setup the interface buttons. tootButton.setOnClickListener(v -> onSendClicked()); pickButton.setOnClickListener(v -> openPickDialog()); visibilityButton.setOnClickListener(v -> showComposeOptions()); contentWarningButton.setOnClickListener(v -> onContentWarningChanged()); emojiButton.setOnClickListener(v -> showEmojis()); hideMediaToggle.setOnClickListener(v -> toggleHideMedia()); TextView actionPhotoTake = findViewById(R.id.action_photo_take); TextView actionPhotoPick = findViewById(R.id.action_photo_pick); int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary); Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor) .sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null, null); Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null, null); actionPhotoTake.setOnClickListener(v -> initiateCameraApp()); actionPhotoPick.setOnClickListener(v -> onMediaPick()); thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size); /* Initialise all the state, or restore it from a previous run, to determine a "starting" * state. */ Status.Visibility startingVisibility = Status.Visibility.UNKNOWN; boolean startingHideText; ArrayList<SavedQueuedMedia> savedMediaQueued = null; if (savedInstanceState != null) { startingVisibility = Status.Visibility .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum())); statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive"); startingHideText = savedInstanceState.getBoolean("statusHideText"); // Keep these until everything needed to put them in the queue is finished initializing. savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued"); // These are for restoring an in-progress commit content operation. InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo")); int previousFlags = savedInstanceState.getInt("commitContentFlags"); if (previousInputContentInfo != null) { onCommitContentInternal(previousInputContentInfo, previousFlags); } photoUploadUri = savedInstanceState.getParcelable("photoUploadUri"); } else { statusMarkSensitive = false; startingHideText = false; photoUploadUri = null; } /* If the composer is started up as a reply to another post, override the "starting" state * based on what the intent from the reply request passes. */ Intent intent = getIntent(); String[] mentionedUsernames = null; ArrayList<String> loadedDraftMediaUris = null; inReplyToId = null; if (intent != null) { if (startingVisibility == Status.Visibility.UNKNOWN) { Status.Visibility preferredVisibility = Status.Visibility.byString( preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString())); Status.Visibility replyVisibility = Status.Visibility .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum())); startingVisibility = Status.Visibility .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum())); } inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA); mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA); String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA); if (contentWarning != null) { startingHideText = !contentWarning.isEmpty(); if (startingHideText) { startingContentWarning = contentWarning; } } // If come from SavedTootActivity String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA); if (!TextUtils.isEmpty(savedTootText)) { startingText = savedTootText; textEditor.setText(savedTootText); } String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA); if (!TextUtils.isEmpty(savedJsonUrls)) { // try to redo a list of media loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() { }.getType()); } int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0); if (savedTootUid != 0) { this.savedTootUid = savedTootUid; } if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) { replyTextView.setVisibility(View.VISIBLE); String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA); replyTextView.setText(getString(R.string.replying_to, username)); Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); replyTextView.setOnClickListener(v -> { TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent()); if (replyContentTextView.getVisibility() != View.VISIBLE) { replyContentTextView.setVisibility(View.VISIBLE); Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up) .sizeDp(12); ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowUpIcon, null); } else { replyContentTextView.setVisibility(View.GONE); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null, arrowDownIcon, null); } }); } if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) { replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA)); } } // After the starting state is finalised, the interface can be set to reflect this state. setStatusVisibility(startingVisibility); updateHideMediaToggle(); updateVisibleCharactersLeft(); // Setup the main text field. textEditor.setOnCommitContentListener(this); final int mentionColour = textEditor.getLinkTextColors().getDefaultColor(); SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour); textEditor.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable editable) { SpanUtilsKt.highlightSpans(editable, mentionColour); updateVisibleCharactersLeft(); } }); textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this)); textEditor.setTokenizer(new MentionTokenizer()); // Add any mentions to the text field when a reply is first composed. if (mentionedUsernames != null) { StringBuilder builder = new StringBuilder(); for (String name : mentionedUsernames) { builder.append('@'); builder.append(name); builder.append(' '); } startingText = builder.toString(); textEditor.setText(startingText); textEditor.setSelection(textEditor.length()); } // work around Android platform bug -> https://issuetracker.google.com/issues/67102093 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) { textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // Initialise the content warning editor. contentWarningEditor.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateVisibleCharactersLeft(); } @Override public void afterTextChanged(Editable s) { } }); showContentWarning(startingHideText); if (startingContentWarning != null) { contentWarningEditor.setText(startingContentWarning); } // Initialise the empty media queue state. waitForMediaLatch = new CountUpDownLatch(); // These can only be added after everything affected by the media queue is initialized. if (!ListUtils.isEmpty(loadedDraftMediaUris)) { for (String uriString : loadedDraftMediaUris) { Uri uri = Uri.parse(uriString); long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (savedMediaQueued != null) { for (SavedQueuedMedia item : savedMediaQueued) { Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize); addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage, item.description); } } else if (intent != null && savedInstanceState == null) { /* Get incoming images being sent through a share action from another app. Only do this * when savedInstanceState is null, otherwise both the images from the intent and the * instance state will be re-queued. */ String type = intent.getType(); if (type != null) { if (type.startsWith("image/")) { List<Uri> uriList = new ArrayList<>(); if (intent.getAction() != null) { switch (intent.getAction()) { case Intent.ACTION_SEND: { Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { uriList.add(uri); } break; } case Intent.ACTION_SEND_MULTIPLE: { ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Uri uri : list) { if (uri != null) { uriList.add(uri); } } } break; } } } for (Uri uri : uriList) { long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri); pickMedia(uri, mediaSize); } } else if (type.equals("text/plain")) { String action = intent.getAction(); if (action != null && action.equals(Intent.ACTION_SEND)) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { int start = Math.max(textEditor.getSelectionStart(), 0); int end = Math.max(textEditor.getSelectionEnd(), 0); int left = Math.min(start, end); int right = Math.max(start, end); textEditor.getText().replace(left, right, text, 0, text.length()); } } } } } textEditor.requestFocus(); }