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:alaindc.memenguage.View.MainActivity.java

@SuppressWarnings("StatementWithEmptyBody")
@Override// w w  w  .java2s .co  m
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_home) {

    } else if (id == R.id.nav_settings) {
        Intent settingsActivity = new Intent(this, SettingsActivity.class);
        startActivity(settingsActivity);
    } else if (id == R.id.nav_send) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyDialogTheme);
        builder.setTitle("Upload Database").setMessage("Are you sure?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        progressDialog.setTitle("Upload");
                        progressDialog.setMessage("Uploading to server... please wait");
                        progressDialog.show();
                        ServerRequests.uploadFile(personId,
                                getApplicationContext().getDatabasePath(Constants.DBNAME),
                                getApplicationContext());
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).create().show();

    } else if (id == R.id.nav_get) {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyDialogTheme);
        builder.setTitle("Download Database").setMessage("Are you sure?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        progressDialog.setTitle("Download");
                        progressDialog.setMessage("Downloading from server... please wait");
                        progressDialog.show();
                        ServerRequests.downloadFile(personId,
                                getApplicationContext().getDatabasePath(Constants.DBNAME),
                                getApplicationContext());
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).create().show();

    } else if (id == R.id.nav_share) {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Memenguage, the best app on the world! Maybe.";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Memento mori!");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    } else if (id == R.id.nav_signin) {
        Intent signinintent = new Intent(this, SignInActivity.class);
        signinintent.setAction(Constants.SIGNIN_LOGOUT);
        startActivity(signinintent);
    } else if (id == R.id.nav_play) {
        Intent playActivity = new Intent(this, PlayActivity.class);
        startActivity(playActivity);
    } else if (id == R.id.nav_stats) {
        Intent statsActivity = new Intent(this, StatsActivity.class);
        startActivity(statsActivity);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java

private void showGooglePlusShareButton(String path) {
    Button shareButton = (Button) mMainActivity.findViewById(R.id.shareButton);
    shareButton.setVisibility(View.VISIBLE);
    final String file = path;
    shareButton.setOnClickListener(new OnClickListener() {
        @Override/* w w  w  .j  a  va2 s. c o  m*/
        public void onClick(View v) {
            File f = new File(file);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
            intent.setPackage("com.google.android.apps.plus");
            try {
                mMainActivity.startActivity(intent);
            } catch (ActivityNotFoundException anfex) {
                intent.setPackage(null);
                mMainActivity.startActivity(intent);
            }
        }
    });
}

From source file:aarddict.android.ArticleViewActivity.java

@Override
public boolean onSearchRequested() {
    Intent intent = getIntent();/*from   w  w w.  jav a 2s . c  o m*/
    String action = intent == null ? null : intent.getAction();
    if (action != null) {
        String word = null;
        if (action.equals(Intent.ACTION_SEARCH)) {
            word = intent.getStringExtra("query");
        } else if (action.equals(Intent.ACTION_SEND)) {
            word = intent.getStringExtra(Intent.EXTRA_TEXT);
        }
        if (word != null) {
            Intent next = new Intent();
            next.setClass(this, LookupActivity.class);
            next.setAction(Intent.ACTION_SEARCH);
            next.putExtra(SearchManager.QUERY, word);
            startActivity(next);
        }
    }
    finish();
    return true;
}

From source file:com.dwdesign.tweetings.fragment.BaseStatusesListFragment.java

@Override
public boolean onMenuItemClick(final MenuItem item) {
    final ParcelableStatus status = mSelectedStatus;
    if (status == null)
        return false;
    final long account_id = getDefaultAccountId(mApplication);
    switch (item.getItemId()) {
    case MENU_VIEW: {
        openStatus(getActivity(), status);
        break;//from  w  ww.j  a  v a  2 s. c o m
    }
    case MENU_SHARE: {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "@" + status.screen_name + ": " + status.text_plain);
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
        break;
    }
    case MENU_TRANSLATE: {
        translate(status);
        break;
    }
    case MENU_RETWEET: {
        if (isMyRetweet(status)) {
            mService.destroyStatus(status.account_id, status.status_id);
        } else {
            final long id_to_retweet = mSelectedStatus.is_retweet && mSelectedStatus.retweet_id > 0
                    ? mSelectedStatus.retweet_id
                    : mSelectedStatus.status_id;
            mService.retweetStatus(status.account_id, id_to_retweet);
        }
        break;
    }
    case MENU_QUOTE: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_QUOTE_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, status.status_id);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, status.screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, status.name);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_ADD_TO_BUFFER: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putBoolean(INTENT_KEY_IS_BUFFER, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final List<String> mentions = new Extractor().extractMentionedScreennames(status.text_plain);
        mentions.remove(status.screen_name);
        mentions.add(0, status.screen_name);
        bundle.putStringArray(INTENT_KEY_MENTIONS, mentions.toArray(new String[mentions.size()]));
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, status.status_id);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_TWEET, status.text_plain);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, status.screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, status.name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_FAV: {
        if (mSelectedStatus.is_favorite) {
            mService.destroyFavorite(status.account_id, status.status_id);
        } else {
            mService.createFavorite(status.account_id, status.status_id);
        }
        break;
    }
    case MENU_CONVERSATION: {
        openConversation(getActivity(), status.account_id, status.status_id);
        break;
    }
    case MENU_DELETE: {
        mService.destroyStatus(status.account_id, status.status_id);
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_STATUS);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_STATUS, status);
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    case MENU_MULTI_SELECT: {
        if (!mApplication.isMultiSelectActive()) {
            mApplication.startMultiSelect();
        }
        final NoDuplicatesLinkedList<Object> list = mApplication.getSelectedItems();
        if (!list.contains(status)) {
            list.add(status);
        }
        break;
    }
    case MENU_BLOCK: {
        mService.createBlock(account_id, status.user_id);
        break;
    }
    case MENU_REPORT_SPAM: {
        mService.reportSpam(account_id, status.user_id);
        break;
    }
    case MENU_MUTE_USER: {
        final String screen_name = status.screen_name;
        final Uri uri = Filters.Users.CONTENT_URI;
        final ContentValues values = new ContentValues();
        final SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE).edit();
        final ContentResolver resolver = getContentResolver();
        values.put(Filters.Users.TEXT, screen_name);
        resolver.delete(uri, Filters.Users.TEXT + " = '" + screen_name + "'", null);
        resolver.insert(uri, values);
        editor.putBoolean(PREFERENCE_KEY_ENABLE_FILTER, true).commit();
        Toast.makeText(getActivity(), R.string.user_muted, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_MAKE_GAP: {
        Uri uri = Statuses.CONTENT_URI;
        final Uri query_uri = buildQueryUri(uri, false);
        ContentResolver mResolver = getContentResolver();
        final ContentValues values = new ContentValues();
        values.put(Statuses.IS_GAP, 1);
        final StringBuilder where = new StringBuilder();
        where.append(Statuses.ACCOUNT_ID + "=" + account_id);
        where.append(" AND " + Statuses.STATUS_ID + "=" + status.status_id);
        mResolver.update(query_uri, values, where.toString(), null);
        getActivity().sendBroadcast(new Intent(BROADCAST_FILTERS_UPDATED).putExtra(INTENT_KEY_SUCCEED, true));
        break;
    }
    case MENU_COPY: {
        final CharSequence text = Html.fromHtml(status.text_html);
        if (ClipboardUtils.setText(getActivity(), text)) {
            Toast.makeText(getActivity(), R.string.text_copied, Toast.LENGTH_SHORT).show();
        }
        break;
    }
    }
    return true;
}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

public static void onActionMenuItemSelected(final RedditPreparedPost post, final Fragment fragmentParent,
        final Action action) {

    final Activity activity = fragmentParent.getSupportActivity();

    switch (action) {

    case UPVOTE://w  w  w  . ja va2 s . c o m
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

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

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

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

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

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

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        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() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.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);
        intent.setData(Uri.parse(post.url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

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

        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() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

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

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            General.copyFile(cacheFile.getInputStream(), dst);
                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

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

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

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

    case GOTO_SUBREDDIT: {

        final RedditSubreddit subreddit = new RedditSubreddit("/r/" + post.src.subreddit,
                "/r/" + post.src.subreddit, true);

        final Intent intent = new Intent(activity, PostListingActivity.class);
        intent.putExtra("subreddit", subreddit);
        activity.startActivityForResult(intent, 1);
        break;
    }

    case USER_PROFILE:
        UserProfileDialog.newInstance(post.src.author).show(activity);
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

    case COMMENTS:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostCommentsSelected(post);
        break;

    case LINK:
        ((RedditPostView.PostSelectionListener) fragmentParent).onPostSelected(post);
        break;

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

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

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

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:com.openerp.addons.messages.MessageComposeActivty.java

/**
 * Handle message intent filter for attachments
 * //from   w w  w . j  a va  2 s.c om
 * @param intent
 */
private void handleIntentFilter(Intent intent) {
    attachments_type.put(ATTACHMENT_TYPE.IMAGE, "image/*");
    attachments_type.put(ATTACHMENT_TYPE.TEXT_FILE, "application/*");

    String action = intent.getAction();
    String type = intent.getType();

    // Single attachment
    if (Intent.ACTION_SEND.equals(action) && type != null) {
        Uri fileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
        file_uris.add(fileUri);
        handleReceivedFile();
    }

    // Multiple Attachments
    if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        ArrayList<Uri> fileUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        file_uris.addAll(fileUris);
        handleReceivedFile();

    }

    // note.note send as mail
    if (intent.hasExtra("note_body")) {
        EditText edtBody = (EditText) findViewById(R.id.edtMessageBody);
        String body = intent.getExtras().getString("note_body");
        edtBody.setText(HTMLHelper.stringToHtml(body));
        is_note_body = true;
    }

}

From source file:org.bwgz.quotation.activity.QuotationActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = false;

    switch (item.getItemId()) {
    case R.id.actionbar_back: {
        Log.d(TAG, String.format("onOptionsItemSelected - actionbar_back"));
        if (history.hasBack()) {
            loadQuote(history.back());/*from  ww  w.  ja  v  a2s . co  m*/
        }

        menu.findItem(R.id.actionbar_back).setEnabled(history.hasBack());
        menu.findItem(R.id.actionbar_forward).setEnabled(history.hasForward());

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_back", null).build());
        result = true;
        break;
    }
    case R.id.actionbar_forward: {
        Log.d(TAG, String.format("onOptionsItemSelected - actionbar_forward"));
        if (history.hasForward()) {
            loadQuote(history.forward());
        }

        menu.findItem(R.id.actionbar_back).setEnabled(history.hasBack());
        menu.findItem(R.id.actionbar_forward).setEnabled(history.hasForward());

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_forward", null).build());
        result = true;
        break;
    }
    case R.id.actionbar_new: {
        loadRandomQuote();

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_new", null).build());
        result = true;
        break;
    }
    case R.id.actionbar_share: {
        CharSequence text = ((TextView) findViewById(R.id.quotation)).getText();
        if (text != null && text.length() != 0) {
            StringBuilder buffer = new StringBuilder();
            buffer.append(text);

            text = ((TextView) findViewById(R.id.author)).getText();
            if (text != null && text.length() != 0) {
                buffer.append(" ... ");
                buffer.append(text);
            }

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, buffer.toString());
            startActivity(Intent.createChooser(intent, getResources().getText(R.string.sharing_quote)));
        }

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_share", null).build());
        result = true;
        break;
    }
    case R.id.settings: {
        Intent intent = new Intent().setClass(this, SettingsActivity.class);
        startActivity(intent);

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_settings", null).build());
        result = true;
        break;
    }
    }

    return result;
}

From source file:com.androzic.MainActivity.java

@Override
public void onWaypointShare(Waypoint waypoint) {
    Intent i = new Intent(android.content.Intent.ACTION_SEND);
    i.setType("text/plain");
    i.putExtra(Intent.EXTRA_SUBJECT, R.string.currentloc);
    String coords = StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude);
    i.putExtra(Intent.EXTRA_TEXT, waypoint.name + " @ " + coords);
    startActivity(Intent.createChooser(i, getString(R.string.menu_share)));
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedPost.java

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

    switch (action) {

    case UPVOTE:/*  w w w.  jav  a2 s .  co m*/
        post.action(activity, RedditAPI.RedditAction.UPVOTE);
        break;

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

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

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

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

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

    case UNHIDE:
        post.action(activity, RedditAPI.RedditAction.UNHIDE);
        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() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        post.action(activity, RedditAPI.RedditAction.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.url;
        intent.setData(Uri.parse(url));
        activity.startActivity(intent);
        break;
    }

    case SELFTEXT_LINKS: {

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

        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() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src);
                    dialog.dismiss();
                }
            });

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

        break;
    }

    case SAVE_IMAGE: {

        final RedditAccount anon = RedditAccountManager.getAnon();

        CacheManager.getInstance(activity)
                .makeRequest(new CacheRequest(General.uriFromString(post.imageUrl), anon, null,
                        Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                        Constants.FileType.IMAGE, false, false, false, activity) {

                    @Override
                    protected void onCallbackException(Throwable t) {
                        BugReportActivity.handleGlobalError(context, t);
                    }

                    @Override
                    protected void onDownloadNecessary() {
                        General.quickToast(context, R.string.download_downloading);
                    }

                    @Override
                    protected void onDownloadStarted() {
                    }

                    @Override
                    protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                            String readableMessage) {
                        final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                                url.toString());
                        General.showResultDialog(activity, error);
                    }

                    @Override
                    protected void onProgress(long bytesRead, long totalBytes) {
                    }

                    @Override
                    protected void onSuccess(CacheManager.ReadableCacheFile cacheFile, long timestamp,
                            UUID session, boolean fromCache, String mimetype) {

                        File dst = new File(
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                General.uriFromString(post.imageUrl).getPath());

                        if (dst.exists()) {
                            int count = 0;

                            while (dst.exists()) {
                                count++;
                                dst = new File(
                                        Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_PICTURES),
                                        count + "_"
                                                + General.uriFromString(post.imageUrl).getPath().substring(1));
                            }
                        }

                        try {
                            final InputStream cacheFileInputStream = cacheFile.getInputStream();

                            if (cacheFileInputStream == null) {
                                notifyFailure(RequestFailureType.CACHE_MISS, null, null,
                                        "Could not find cached image");
                                return;
                            }

                            General.copyFile(cacheFileInputStream, dst);

                        } catch (IOException e) {
                            notifyFailure(RequestFailureType.STORAGE, e, null, "Could not copy file");
                            return;
                        }

                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.parse("file://" + dst.getAbsolutePath())));

                        General.quickToast(context, context.getString(R.string.action_save_image_success) + " "
                                + dst.getAbsolutePath());
                    }
                });

        break;
    }

    case SHARE: {

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

    case SHARE_COMMENTS: {

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.title);
        mailer.putExtra(Intent.EXTRA_TEXT,
                Constants.Reddit.getUri(Constants.Reddit.PATH_COMMENTS + post.idAlone).toString());
        activity.startActivity(
                Intent.createChooser(mailer, activity.getString(R.string.action_share_comments)));
        break;
    }

    case COPY: {

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

    case GOTO_SUBREDDIT: {

        try {
            final Intent intent = new Intent(activity, PostListingActivity.class);
            intent.setData(SubredditPostListURL.getSubreddit(post.src.subreddit).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.author).toString());
        break;

    case PROPERTIES:
        PostPropertiesDialog.newInstance(post.src).show(activity);
        break;

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

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

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

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

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

    case REPLY:
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", post.idAndType);
        activity.startActivity(intent);
        break;
    }
}

From source file:net.kourlas.voipms_sms.activities.ConversationActivity.java

@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
    if (menuItem.getItemId() == R.id.resend_button) {
        for (int i = 0; i < adapter.getItemCount(); i++) {
            if (adapter.isItemChecked(i)) {
                sendMessage(adapter.getItem(i).getDatabaseId());
                break;
            }//  ww w  . ja  v  a  2  s  . c  o m
        }

        actionMode.finish();
        return true;
    } else if (menuItem.getItemId() == R.id.info_button) {
        Message message = null;
        for (int i = 0; i < adapter.getItemCount(); i++) {
            if (adapter.isItemChecked(i)) {
                message = adapter.getItem(i);
                break;
            }
        }

        if (message != null) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String dialogText;
            if (message.getType() == Message.Type.INCOMING) {
                dialogText = (message.getVoipId() == null ? ""
                        : (getString(R.string.conversation_info_id) + " " + message.getVoipId() + "\n"))
                        + getString(R.string.conversation_info_to) + " "
                        + Utils.getFormattedPhoneNumber(message.getDid()) + "\n"
                        + getString(R.string.conversation_info_from) + " "
                        + Utils.getFormattedPhoneNumber(message.getContact()) + "\n"
                        + getString(R.string.conversation_info_date) + " "
                        + dateFormat.format(message.getDate());
            } else {
                dialogText = (message.getVoipId() == null ? ""
                        : (getString(R.string.conversation_info_id) + " " + message.getVoipId() + "\n"))
                        + getString(R.string.conversation_info_to) + " "
                        + Utils.getFormattedPhoneNumber(message.getContact()) + "\n"
                        + getString(R.string.conversation_info_from) + " "
                        + Utils.getFormattedPhoneNumber(message.getDid()) + "\n"
                        + getString(R.string.conversation_info_date) + " "
                        + dateFormat.format(message.getDate());
            }
            Utils.showAlertDialog(this, getString(R.string.conversation_info_title), dialogText,
                    getString(R.string.ok), null, null, null);
        }

        actionMode.finish();
        return true;
    } else if (menuItem.getItemId() == R.id.copy_button) {
        Message message = null;
        for (int i = 0; i < adapter.getItemCount(); i++) {
            if (adapter.isItemChecked(i)) {
                message = adapter.getItem(i);
                break;
            }
        }

        if (message != null) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Text message", message.getText());
            clipboard.setPrimaryClip(clip);
        }

        actionMode.finish();
        return true;
    } else if (menuItem.getItemId() == R.id.share_button) {
        Message message = null;
        for (int i = 0; i < adapter.getItemCount(); i++) {
            if (adapter.isItemChecked(i)) {
                message = adapter.getItem(i);
                break;
            }
        }

        if (message != null) {
            Intent intent = new Intent(android.content.Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(android.content.Intent.EXTRA_TEXT, message.getText());
            startActivity(Intent.createChooser(intent, null));
        }

        actionMode.finish();
        return true;
    } else if (menuItem.getItemId() == R.id.delete_button) {
        List<Long> databaseIds = new ArrayList<>();
        for (int i = 0; i < adapter.getItemCount(); i++) {
            if (adapter.isItemChecked(i)) {
                databaseIds.add(adapter.getItem(i).getDatabaseId());
            }
        }

        Long[] databaseIdsArray = new Long[databaseIds.size()];
        databaseIds.toArray(databaseIdsArray);
        deleteMessages(databaseIdsArray);

        actionMode.finish();
        return true;
    } else {
        return false;
    }
}