Example usage for android.content Intent ACTION_SEND

List of usage examples for android.content Intent ACTION_SEND

Introduction

In this page you can find the example usage for android.content Intent ACTION_SEND.

Prototype

String ACTION_SEND

To view the source code for android.content Intent ACTION_SEND.

Click Source Link

Document

Activity Action: Deliver some data to someone else.

Usage

From source file:com.slim.turboeditor.activity.MainActivity.java

/**
 * Parses the intent//from   w  w  w  .  j a va 2s .  c  o m
 */
private void parseIntent(Intent intent) {
    final String action = intent.getAction();
    final String type = intent.getType();

    if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action)
            || Intent.ACTION_PICK.equals(action) && type != null) {
        Uri uri = intent.getData();
        File newFile = new File(uri.getPath());
        newFileToOpen(newFile, "");
    } else if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            newFileToOpen(null, intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    }
}

From source file:com.ibuildapp.romanblack.MultiContactsPlugin.ContactDetailsActivity.java

/**
 * Opens a contact detial pare depending on contact type.
 *
 * @param position contact position//from w  w w.  ja  va  2  s.c om
 */
private void listViewItemClick(int position) {
    try {//ErrorLogging

        int type = neededContacts.get(position).getType();
        switch (type) {
        case 0: {
        }
            break;
        case 1: {
            final String phoneNumber = neededContacts.get(position).getDescription();

            new CallDialog(this, phoneNumber, new CallDialog.ActionListener() {
                @Override
                public void onCall(DialogInterface dialog) {
                    dialog.dismiss();
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:" + phoneNumber));
                    startActivity(callIntent);
                    overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);
                }

                @Override
                public void onAddContact(DialogInterface dialog) {
                    createNewContact(person.getName(), person.getPhone(), person.getEmail());
                    dialog.dismiss();
                }

                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                }
            }).show();
        }
            break;
        case 2: {
            String email = neededContacts.get(position).getDescription();
            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("text/html");
            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { email });
            startActivity(emailIntent);
            overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);
        }
            break;
        case 3: {
            String url = neededContacts.get(position).getDescription();

            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                url = "http://" + url;
            }

            Intent intent = new Intent(this, ContactsWebActivity.class);
            intent.putExtra("link", url);
            startActivity(intent);
            overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);
        }
            break;
        case 4: {
            Intent intent = new Intent(this, NativeMapActivity.class);
            intent.putExtra("person", person);
            startActivity(intent);
            overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);
        }
            break;
        }

    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
    }
}

From source file:net.bytten.comicviewer.ComicViewerActivity.java

public void shareComicImage() {
    if (comicInfo == null || comicInfo.getImage() == null) {
        toast("No image loaded.");
        return;//from  w  ww  .j  a v  a2  s  . c om
    }

    new Utility.CancellableAsyncTaskWithProgressDialog<Uri, File>(getStringAppName()) {
        Throwable e;

        @Override
        protected File doInBackground(Uri... params) {
            try {
                File file = new File(getApplicationContext().getExternalCacheDir(),
                        comicDef.getComicTitleAbbrev() + "-" + params[0].getLastPathSegment());
                Utility.blockingSaveFile(file, params[0]);
                return file;

            } catch (InterruptedException ex) {
                return null;
            } catch (Throwable ex) {
                e = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            super.onPostExecute(result);
            if (result != null && e == null) {

                try {
                    Uri uri = Uri.fromFile(result);
                    Intent intent = new Intent(Intent.ACTION_SEND, null);
                    intent.setType(Utility.getContentType(uri));
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(intent, "Share image..."));
                    return;
                } catch (MalformedURLException ex) {
                    e = ex;
                } catch (IOException ex) {
                    e = ex;
                }
            }
            e.printStackTrace();
            failed("Couldn't save attachment: " + e);
        }

    }.start(this, "Saving image...", new Uri[] { comicInfo.getImage() });
}

From source file:com.dycody.android.idealnote.DetailFragment.java

private void handleIntents() {
    Intent i = mainActivity.getIntent();

    if (IntentChecker.checkAction(i, Constants.ACTION_MERGE)) {
        noteOriginal = new Note();
        note = new Note(noteOriginal);
        noteTmp = getArguments().getParcelable(Constants.INTENT_NOTE);
        if (i.getStringArrayListExtra("merged_notes") != null) {
            mergedNotesIds = i.getStringArrayListExtra("merged_notes");
        }/*  ww  w . java 2s. co m*/
    }

    // Action called from home shortcut
    if (IntentChecker.checkAction(i, Constants.ACTION_SHORTCUT, Constants.ACTION_NOTIFICATION_CLICK)) {
        afterSavedReturnsToList = false;
        noteOriginal = DbHelper.getInstance().getNote(i.getLongExtra(Constants.INTENT_KEY, 0));
        // Checks if the note pointed from the shortcut has been deleted
        try {
            note = new Note(noteOriginal);
            noteTmp = new Note(noteOriginal);
        } catch (NullPointerException e) {
            mainActivity.showToast(getText(R.string.shortcut_note_deleted), Toast.LENGTH_LONG);
            mainActivity.finish();
        }
    }

    // Check if is launched from a widget
    if (IntentChecker.checkAction(i, Constants.ACTION_WIDGET, Constants.ACTION_TAKE_PHOTO)) {

        afterSavedReturnsToList = false;
        showKeyboard = true;

        //  with tags to set tag
        if (i.hasExtra(Constants.INTENT_WIDGET)) {
            String widgetId = i.getExtras().get(Constants.INTENT_WIDGET).toString();
            if (widgetId != null) {
                String sqlCondition = prefs.getString(Constants.PREF_WIDGET_PREFIX + widgetId, "");
                String categoryId = TextHelper.checkIntentCategory(sqlCondition);
                if (categoryId != null) {
                    Category category;
                    try {
                        category = DbHelper.getInstance().getCategory(Long.parseLong(categoryId));
                        noteTmp = new Note();
                        noteTmp.setCategory(category);
                    } catch (NumberFormatException e) {
                        Log.e(Constants.TAG, "Category with not-numeric value!", e);
                    }
                }
            }
        }

        // Sub-action is to take a photo
        if (IntentChecker.checkAction(i, Constants.ACTION_TAKE_PHOTO)) {
            takePhoto();
        }
    }

    /**
     * Handles third party apps requests of sharing
     */
    if (IntentChecker.checkAction(i, Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE,
            Constants.INTENT_GOOGLE_NOW) && i.getType() != null) {

        afterSavedReturnsToList = false;

        if (noteTmp == null)
            noteTmp = new Note();

        // Text title
        String title = i.getStringExtra(Intent.EXTRA_SUBJECT);
        if (title != null) {
            noteTmp.setTitle(title);
        }

        // Text content
        String content = i.getStringExtra(Intent.EXTRA_TEXT);
        if (content != null) {
            noteTmp.setContent(content);
        }

        // Single attachment data
        Uri uri = i.getParcelableExtra(Intent.EXTRA_STREAM);
        // Due to the fact that Google Now passes intent as text but with
        // audio recording attached the case must be handled in specific way
        if (uri != null && !Constants.INTENT_GOOGLE_NOW.equals(i.getAction())) {
            String name = FileHelper.getNameFromUri(mainActivity, uri);
            new AttachmentTask(this, uri, name, this).execute();
        }

        // Multiple attachment data
        ArrayList<Uri> uris = i.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        if (uris != null) {
            for (Uri uriSingle : uris) {
                String name = FileHelper.getNameFromUri(mainActivity, uriSingle);
                new AttachmentTask(this, uriSingle, name, this).execute();
            }
        }
    }

    if (IntentChecker.checkAction(i, Intent.ACTION_MAIN, Constants.ACTION_WIDGET_SHOW_LIST,
            Constants.ACTION_SHORTCUT_WIDGET, Constants.ACTION_WIDGET)) {
        showKeyboard = true;
    }

    i.setAction(null);
}

From source file:com.cerema.cloud2.ui.activity.Uploader.java

private void prepareStreamsToUpload() {
    if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
        mStreamsToUpload = new ArrayList<Parcelable>();
        mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
    } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
        mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    }/*from w w  w . j av a2 s  .  co m*/
}

From source file:pl.bcichecki.rms.client.android.fragments.EventsListFragment.java

private void performActionShare(ActionMode mode, MenuItem item, Event selectedEvent) {
    ShareActionProvider shareActionProvider = (ShareActionProvider) item.getActionProvider();
    if (shareActionProvider != null) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType(AppConstants.CONTENT_TEXT_PLAIN);
        intent.putExtra(android.content.Intent.EXTRA_TEXT,
                new EventTextPrettyPrinter(getActivity()).print(selectedEvent));
        shareActionProvider.setShareHistoryFileName(null);
        shareActionProvider.setShareIntent(intent);

        Log.d(TAG, "Event " + selectedEvent + " was succesfully shared.");
    }/* www  .  j ava 2 s  . co  m*/
}

From source file:com.piusvelte.taplock.client.core.TapLockSettings.java

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*from   ww  w.j av  a2  s.c  o  m*/
    if (mInWriteMode) {
        if (intent != null) {
            String action = intent.getAction();
            if (mInWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                    && intent.hasExtra(EXTRA_DEVICE_NAME)) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                String name = intent.getStringExtra(EXTRA_DEVICE_NAME);
                if ((tag != null) && (name != null)) {
                    // write the device and address
                    String lang = "en";
                    // don't write the passphrase!
                    byte[] textBytes = name.getBytes();
                    byte[] langBytes = null;
                    int langLength = 0;
                    try {
                        langBytes = lang.getBytes("US-ASCII");
                        langLength = langBytes.length;
                    } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, e.toString());
                    }
                    int textLength = textBytes.length;
                    byte[] payload = new byte[1 + langLength + textLength];

                    // set status byte (see NDEF spec for actual bits)
                    payload[0] = (byte) langLength;

                    // copy langbytes and textbytes into payload
                    if (langBytes != null) {
                        System.arraycopy(langBytes, 0, payload, 1, langLength);
                    }
                    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
                    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                            new byte[0], payload);
                    NdefMessage message = new NdefMessage(
                            new NdefRecord[] { record, NdefRecord.createApplicationRecord(getPackageName()) });
                    // Get an instance of Ndef for the tag.
                    Ndef ndef = Ndef.get(tag);
                    if (ndef != null) {
                        try {
                            ndef.connect();
                            if (ndef.isWritable()) {
                                ndef.writeNdefMessage(message);
                            }
                            ndef.close();
                            Toast.makeText(this, "tag written", Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        } catch (FormatException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        NdefFormatable format = NdefFormatable.get(tag);
                        if (format != null) {
                            try {
                                format.connect();
                                format.format(message);
                                format.close();
                                Toast.makeText(getApplicationContext(), "tag written", Toast.LENGTH_LONG);
                            } catch (IOException e) {
                                Log.e(TAG, e.toString());
                            } catch (FormatException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    mNfcAdapter.disableForegroundDispatch(this);
                }
            }
        }
        mInWriteMode = false;
    } else {
        SharedPreferences sp = getSharedPreferences(KEY_PREFS, MODE_PRIVATE);
        onSharedPreferenceChanged(sp, KEY_DEVICES);
        // check if configuring a widget
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                final String[] displayNames = TapLock.getDeviceNames(mDevices);
                final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle("Select device for widget")
                            .setItems(displayNames, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // set the successful widget result
                                    Intent resultValue = new Intent();
                                    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                                    setResult(RESULT_OK, resultValue);

                                    // broadcast the new widget to update
                                    JSONObject deviceJObj = mDevices.get(which);
                                    dialog.cancel();
                                    TapLockSettings.this.finish();
                                    try {
                                        sendBroadcast(TapLock
                                                .getPackageIntent(TapLockSettings.this, TapLockWidget.class)
                                                .setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
                                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                                                .putExtra(EXTRA_DEVICE_NAME, deviceJObj.getString(KEY_NAME)));
                                    } catch (JSONException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                }
                            }).create();
                    mDialog.show();
                }
            }
        }
        // start the service before binding so that the service stays around for faster future connections
        startService(TapLock.getPackageIntent(this, TapLockService.class));
        bindService(TapLock.getPackageIntent(this, TapLockService.class), this, BIND_AUTO_CREATE);

        int serverVersion = sp.getInt(KEY_SERVER_VERSION, 0);
        if (mShowTapLockSettingsInfo && (mDevices.size() == 0)) {
            if (serverVersion < SERVER_VERSION)
                sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mShowTapLockSettingsInfo = false;
            Intent i = TapLock.getPackageIntent(this, TapLockInfo.class);
            i.putExtra(EXTRA_INFO, getString(R.string.info_taplocksettings));
            startActivity(i);
        } else if (serverVersion < SERVER_VERSION) {
            // TapLockServer has been updated
            sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_hasupdate)
                    .setMessage(R.string.msg_hasupdate)
                    .setNeutralButton(R.string.button_getserver, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                    .setTitle(R.string.msg_pickinstaller)
                                    .setItems(R.array.installer_entries, new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                            final String installer_file = getResources()
                                                    .getStringArray(R.array.installer_values)[which];

                                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                                    .setTitle(R.string.msg_pickdownloader)
                                                    .setItems(R.array.download_entries,
                                                            new DialogInterface.OnClickListener() {

                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int which) {
                                                                    dialog.cancel();
                                                                    String action = getResources()
                                                                            .getStringArray(
                                                                                    R.array.download_values)[which];
                                                                    if (ACTION_DOWNLOAD_SDCARD.equals(action)
                                                                            && copyFileToSDCard(installer_file))
                                                                        Toast.makeText(TapLockSettings.this,
                                                                                "Done!", Toast.LENGTH_SHORT)
                                                                                .show();
                                                                    else if (ACTION_DOWNLOAD_EMAIL
                                                                            .equals(action)
                                                                            && copyFileToSDCard(
                                                                                    installer_file)) {
                                                                        Intent emailIntent = new Intent(
                                                                                android.content.Intent.ACTION_SEND);
                                                                        emailIntent.setType(
                                                                                "application/java-archive");
                                                                        emailIntent.putExtra(Intent.EXTRA_TEXT,
                                                                                getString(
                                                                                        R.string.email_instructions));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_SUBJECT,
                                                                                getString(R.string.app_name));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_STREAM,
                                                                                Uri.parse("file://"
                                                                                        + Environment
                                                                                                .getExternalStorageDirectory()
                                                                                                .getPath()
                                                                                        + "/"
                                                                                        + installer_file));
                                                                        startActivity(Intent.createChooser(
                                                                                emailIntent, getString(
                                                                                        R.string.button_getserver)));
                                                                    }
                                                                }

                                                            })
                                                    .create();
                                            mDialog.show();
                                        }
                                    }).create();
                            mDialog.show();
                        }
                    }).create();
            mDialog.show();
        }
    }
}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    mService = getTweetingsApplication().getServiceInterface();
    mResolver = getContentResolver();//from  ww w.  jav  a  2  s . co m
    super.onCreate(savedInstanceState);
    setContentView(R.layout.compose);
    mActionBar = getSupportActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(true);

    mUploadProvider = mPreferences.getString(PREFERENCE_KEY_IMAGE_UPLOADER, null);

    final Bundle bundle = savedInstanceState != null ? savedInstanceState : getIntent().getExtras();
    final long account_id = bundle != null ? bundle.getLong(INTENT_KEY_ACCOUNT_ID) : -1;
    mAccountIds = bundle != null ? bundle.getLongArray(INTENT_KEY_IDS) : null;
    mInReplyToStatusId = bundle != null ? bundle.getLong(INTENT_KEY_IN_REPLY_TO_ID) : -1;
    mInReplyToScreenName = bundle != null ? bundle.getString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME) : null;
    mInReplyToName = bundle != null ? bundle.getString(INTENT_KEY_IN_REPLY_TO_NAME) : null;
    mInReplyToText = bundle != null ? bundle.getString(INTENT_KEY_IN_REPLY_TO_TWEET) : null;
    mIsImageAttached = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_IMAGE_ATTACHED) : false;
    mIsPhotoAttached = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_PHOTO_ATTACHED) : false;
    mImageUri = bundle != null ? (Uri) bundle.getParcelable(INTENT_KEY_IMAGE_URI) : null;
    final String[] mentions = bundle != null ? bundle.getStringArray(INTENT_KEY_MENTIONS) : null;
    final String account_username = getAccountUsername(this, account_id);
    int text_selection_start = -1;
    mIsBuffer = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_BUFFER, false) : false;

    if (mInReplyToStatusId > 0) {
        if (bundle != null && bundle.getString(INTENT_KEY_TEXT) != null
                && (mentions == null || mentions.length < 1)) {
            mText = bundle.getString(INTENT_KEY_TEXT);
        } else if (mentions != null) {
            final StringBuilder builder = new StringBuilder();
            for (final String mention : mentions) {
                if (mentions.length == 1 && mentions[0].equalsIgnoreCase(account_username)) {
                    builder.append('@' + account_username + ' ');
                } else if (!mention.equalsIgnoreCase(account_username)) {
                    builder.append('@' + mention + ' ');
                }
            }
            mText = builder.toString();
            text_selection_start = mText.indexOf(' ') + 1;
        }

        mIsQuote = bundle != null ? bundle.getBoolean(INTENT_KEY_IS_QUOTE, false) : false;

        final boolean display_name = mPreferences.getBoolean(PREFERENCE_KEY_DISPLAY_NAME, false);
        final String name = display_name ? mInReplyToName : mInReplyToScreenName;
        if (name != null) {
            setTitle(getString(mIsQuote ? R.string.quote_user : R.string.reply_to, name));
        }
        if (mAccountIds == null || mAccountIds.length == 0) {
            mAccountIds = new long[] { account_id };
        }
        TextView replyText = (TextView) findViewById(R.id.reply_text);
        if (!isNullOrEmpty(mInReplyToText)) {
            replyText.setVisibility(View.VISIBLE);
            replyText.setText(mInReplyToText);
        } else {
            replyText.setVisibility(View.GONE);
        }
    } else {
        if (mentions != null) {
            final StringBuilder builder = new StringBuilder();
            for (final String mention : mentions) {
                if (mentions.length == 1 && mentions[0].equalsIgnoreCase(account_username)) {
                    builder.append('@' + account_username + ' ');
                } else if (!mention.equalsIgnoreCase(account_username)) {
                    builder.append('@' + mention + ' ');
                }
            }
            mText = builder.toString();
        }
        if (mAccountIds == null || mAccountIds.length == 0) {
            final long[] ids_in_prefs = ArrayUtils
                    .fromString(mPreferences.getString(PREFERENCE_KEY_COMPOSE_ACCOUNTS, null), ',');
            final long[] activated_ids = getActivatedAccountIds(this);
            final long[] intersection = ArrayUtils.intersection(ids_in_prefs, activated_ids);
            mAccountIds = intersection.length > 0 ? intersection : activated_ids;
        }
        final String action = getIntent().getAction();
        if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
            setTitle(R.string.share);
            final Bundle extras = getIntent().getExtras();
            if (extras != null) {
                if (mText == null) {
                    final CharSequence extra_subject = extras.getCharSequence(Intent.EXTRA_SUBJECT);
                    final CharSequence extra_text = extras.getCharSequence(Intent.EXTRA_TEXT);
                    mText = getShareStatus(this, parseString(extra_subject), parseString(extra_text));
                } else {
                    mText = bundle.getString(INTENT_KEY_TEXT);
                }
                if (mImageUri == null) {
                    final Uri extra_stream = extras.getParcelable(Intent.EXTRA_STREAM);
                    final String content_type = getIntent().getType();
                    if (extra_stream != null && content_type != null && content_type.startsWith("image/")) {
                        final String real_path = getImagePathFromUri(this, extra_stream);
                        final File file = real_path != null ? new File(real_path) : null;
                        if (file != null && file.exists()) {
                            mImageUri = Uri.fromFile(file);
                            mIsImageAttached = true;
                            mIsPhotoAttached = false;
                        } else {
                            mImageUri = null;
                            mIsImageAttached = false;
                        }
                    }
                }
            }
        } else if (bundle != null) {

            if (bundle.getString(INTENT_KEY_TEXT) != null) {
                mText = bundle.getString(INTENT_KEY_TEXT);
            }
        }
    }

    final File image_file = mImageUri != null && "file".equals(mImageUri.getScheme())
            ? new File(mImageUri.getPath())
            : null;
    final boolean image_file_valid = image_file != null && image_file.exists();
    mImageThumbnailPreview.setVisibility(image_file_valid ? View.VISIBLE : View.GONE);
    if (image_file_valid) {
        reloadAttachedImageThumbnail(image_file);
    }

    mImageThumbnailPreview.setOnClickListener(this);
    mImageThumbnailPreview.setOnLongClickListener(this);
    mMenuBar.setOnMenuItemClickListener(this);
    mMenuBar.inflate(R.menu.menu_compose);
    mMenuBar.show();
    if (mPreferences.getBoolean(PREFERENCE_KEY_QUICK_SEND, false)) {
        mEditText.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
        mEditText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
        mEditText.setImeOptions(EditorInfo.IME_ACTION_GO);
        mEditText.setOnEditorActionListener(this);
    }
    mEditText.addTextChangedListener(this);
    if (mText != null) {
        mEditText.setText(mText);
        if (mIsQuote) {
            mEditText.setSelection(0);
        } else if (text_selection_start != -1 && text_selection_start < mEditText.length()
                && mEditText.length() > 0) {
            mEditText.setSelection(text_selection_start, mEditText.length() - 1);
        } else if (mEditText.length() > 0) {
            mEditText.setSelection(mEditText.length());
        }
    }
    invalidateSupportOptionsMenu();
    setMenu();
    if (mColorIndicator != null) {
        mColorIndicator.setOrientation(ColorView.VERTICAL);
        mColorIndicator.setColor(getAccountColors(this, mAccountIds));
    }
    mContentModified = savedInstanceState != null ? savedInstanceState.getBoolean(INTENT_KEY_CONTENT_MODIFIED)
            : false;
    mIsPossiblySensitive = savedInstanceState != null
            ? savedInstanceState.getBoolean(INTENT_KEY_IS_POSSIBLY_SENSITIVE)
            : false;
}

From source file:com.wellsandwhistles.android.redditsp.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final AppCompatActivity activity,
        final Action action) {

    switch (action) {

    case UPVOTE:/* ww w.  j a va  2  s  . c o  m*/
        post.action(activity, RedditAPI.ACTION_UPVOTE);
        break;

    case DOWNVOTE:
        post.action(activity, RedditAPI.ACTION_DOWNVOTE);
        break;

    case UNVOTE:
        post.action(activity, RedditAPI.ACTION_UNVOTE);
        break;

    case SAVE:
        post.action(activity, RedditAPI.ACTION_SAVE);
        break;

    case UNSAVE:
        post.action(activity, RedditAPI.ACTION_UNSAVE);
        break;

    case HIDE:
        post.action(activity, RedditAPI.ACTION_HIDE);
        break;

    case UNHIDE:
        post.action(activity, RedditAPI.ACTION_UNHIDE);
        break;
    case EDIT:
        final Intent editIntent = new Intent(activity, CommentEditActivity.class);
        editIntent.putExtra("commentIdAndType", post.src.getIdAndType());
        editIntent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(post.src.getRawSelfText()));
        editIntent.putExtra("isSelfPost", true);
        activity.startActivity(editIntent);
        break;

    case DELETE:
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.ACTION_DELETE);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;

    case REPORT:

        new AlertDialog.Builder(activity).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.ACTION_REPORT);
                        // TODO update the view to show the result
                        // TODO don't forget, this also hides
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case EXTERNAL: {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl()
                : post.src.getUrl();
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

        final HashSet<String> linksInComment = LinkHandler
                .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.getRawSelfText()));

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, R.string.error_toast_no_urls_in_self);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src.getSrc());
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_selftext_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;
    }

    case SAVE_IMAGE: {

        ((BaseActivity) activity).requestPermissionWithCallback(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                new SaveImageCallback(activity, post.src.getUrl()));
        break;
    }

    case SHARE: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, post.src.getTitle());
        mailer.putExtra(Intent.EXTRA_TEXT, post.src.getUrl());
        activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share)));
        break;
    }

    case SHARE_COMMENTS: {

        final boolean shareAsPermalink = PrefsUtility.pref_behaviour_share_permalink(activity,
                PreferenceManager.getDefaultSharedPreferences(activity));

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.src.getTitle());
        if (shareAsPermalink) {
            mailer.putExtra(Intent.EXTRA_TEXT,
                    Constants.Reddit.getNonAPIUri(post.src.getPermalink()).toString());
        } else {
            mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit
                    .getNonAPIUri(Constants.Reddit.PATH_COMMENTS + post.src.getIdAlone()).toString());
        }
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case SHARE_IMAGE: {

        ((BaseActivity) activity).requestPermissionWithCallback(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                new ShareImageCallback(activity, post.src.getUrl()));

        break;
    }

    case COPY: {

        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        manager.setText(post.src.getUrl());
        break;
    }

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.getSubreddit()).generateJsonUri());
            activity.startActivityForResult(intent, 1);

        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show();
        }

        break;
    }

    case USER_PROFILE:
        LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.getAuthor()).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src.getSrc()).show(activity.getSupportFragmentManager(), null);
        break;

    case COMMENTS:
        ((PostSelectionListener) activity).onPostCommentsSelected(post);

        new Thread() {
            @Override
            public void run() {
                post.markAsRead(activity);
            }
        }.start();

        break;

    case LINK:
        ((PostSelectionListener) activity).onPostSelected(post);
        break;

    case COMMENTS_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((PostSelectionListener) activity).onPostCommentsSelected(post);
        break;

    case LINK_SWITCH:
        if (!(activity instanceof MainActivity))
            activity.finish();
        ((PostSelectionListener) activity).onPostSelected(post);
        break;

    case ACTION_MENU:
        showActionMenu(activity, post);
        break;

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra(CommentReplyActivity.PARENT_ID_AND_TYPE_KEY, post.src.getIdAndType());
        intent.putExtra(CommentReplyActivity.PARENT_MARKDOWN_KEY, post.src.getUnescapedSelfText());
        activity.startActivity(intent);
        break;

    case BACK:
        activity.onBackPressed();
        break;

    case PIN:

        try {
            String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit());
            List<String> pinnedSubreddits = PrefsUtility.pref_pinned_subreddits(activity,
                    PreferenceManager.getDefaultSharedPreferences(activity));
            if (!pinnedSubreddits.contains(subredditCanonicalName)) {
                PrefsUtility.pref_pinned_subreddits_add(activity,
                        PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName);
            } else {
                Toast.makeText(activity, R.string.mainmenu_toast_pinned, Toast.LENGTH_SHORT).show();
            }
        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            throw new RuntimeException(e);
        }

        break;

    case UNPIN:

        try {
            String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit());
            List<String> pinnedSubreddits = PrefsUtility.pref_pinned_subreddits(activity,
                    PreferenceManager.getDefaultSharedPreferences(activity));
            if (pinnedSubreddits.contains(subredditCanonicalName)) {
                PrefsUtility.pref_pinned_subreddits_remove(activity,
                        PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName);
            } else {
                Toast.makeText(activity, R.string.mainmenu_toast_not_pinned, Toast.LENGTH_SHORT).show();
            }
        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            throw new RuntimeException(e);
        }
        break;

    case BLOCK:

        try {
            String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit());
            List<String> blockedSubreddits = PrefsUtility.pref_blocked_subreddits(activity,
                    PreferenceManager.getDefaultSharedPreferences(activity));
            if (!blockedSubreddits.contains(subredditCanonicalName)) {
                PrefsUtility.pref_blocked_subreddits_add(activity,
                        PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName);
            } else {
                Toast.makeText(activity, R.string.mainmenu_toast_blocked, Toast.LENGTH_SHORT).show();
            }
        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            throw new RuntimeException(e);
        }
        break;

    case UNBLOCK:

        try {
            String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit());
            List<String> blockedSubreddits = PrefsUtility.pref_blocked_subreddits(activity,
                    PreferenceManager.getDefaultSharedPreferences(activity));
            if (blockedSubreddits.contains(subredditCanonicalName)) {
                PrefsUtility.pref_blocked_subreddits_remove(activity,
                        PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName);
            } else {
                Toast.makeText(activity, R.string.mainmenu_toast_not_blocked, Toast.LENGTH_SHORT).show();
            }
        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            throw new RuntimeException(e);
        }
        break;

    case SUBSCRIBE:

        try {
            String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit());
            RedditSubredditSubscriptionManager subMan = RedditSubredditSubscriptionManager
                    .getSingleton(activity, RedditAccountManager.getInstance(activity).getDefaultAccount());

            if (subMan.getSubscriptionState(
                    subredditCanonicalName) == RedditSubredditSubscriptionManager.SubredditSubscriptionState.NOT_SUBSCRIBED) {
                subMan.subscribe(subredditCanonicalName, activity);
                Toast.makeText(activity, R.string.options_subscribing, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, R.string.mainmenu_toast_subscribed, Toast.LENGTH_SHORT).show();
            }
        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            throw new RuntimeException(e);
        }
        break;

    case UNSUBSCRIBE:

        try {
            String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit());
            RedditSubredditSubscriptionManager subMan = RedditSubredditSubscriptionManager
                    .getSingleton(activity, RedditAccountManager.getInstance(activity).getDefaultAccount());
            if (subMan.getSubscriptionState(
                    subredditCanonicalName) == RedditSubredditSubscriptionManager.SubredditSubscriptionState.SUBSCRIBED) {
                subMan.unsubscribe(subredditCanonicalName, activity);
                Toast.makeText(activity, R.string.options_unsubscribing, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, R.string.mainmenu_toast_not_subscribed, Toast.LENGTH_SHORT).show();
            }
        } catch (RedditSubreddit.InvalidSubredditNameException e) {
            throw new RuntimeException(e);
        }
        break;
    }
}

From source file:gr.scify.newsum.ui.SearchViewActivity.java

private void Sendmail() {
    TextView title = (TextView) findViewById(R.id.title);
    String emailSubject = title.getText().toString();

    // track the Send mail action
    if (getAnalyticsPref()) {
        EasyTracker.getTracker().sendEvent(SHARING_ACTION, "Send Mail", emailSubject, 0l);
    }/* ww  w  .j  a va 2 s.  c om*/
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("text/html");
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "NewSum app : " + emailSubject);
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(sText));
    startActivity(Intent.createChooser(emailIntent, "Email:"));

}