Example usage for android.text ClipboardManager setText

List of usage examples for android.text ClipboardManager setText

Introduction

In this page you can find the example usage for android.text ClipboardManager setText.

Prototype

public abstract void setText(CharSequence text);

Source Link

Document

Sets the contents of the clipboard to the specified text.

Usage

From source file:com.fbbackup.ImageDetailActivity.java

private void setListener() {
    btn_share.setOnClickListener(new Button.OnClickListener() {

        @Override// w  ww. j a  v  a2s . c om
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Gets a handle to the clipboard service.
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(clipBoardText);

            PackageManager pm = getPackageManager();
            Intent intent = pm.getLaunchIntentForPackage("jp.naver.line.android");

            File file = new File(extStorageDirectory + "/DCIM/FBBackup/test.jpg");

            Uri outputFileUri = Uri.fromFile(file);

            String[] path = { extStorageDirectory + "/DCIM/FBBackup/test.jpg" };
            //            MediaScannerConnection.scanFile(this, path, null,  
            //                  new MediaScannerConnection.OnScanCompletedListener() {
            //                  public void onScanCompleted(String path, Uri uri) {
            //                      Log.i("ExternalStorage", "Scanned " + path + ":");
            //                      Log.i("ExternalStorage", "-> uri=" + uri);
            //                  }
            //            });

            MediaScannerConnection.scanFile(getApplicationContext(), path, null, null);

            Log.w("RyanWang", outputFileUri.getPath());

            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, outputFileUri);
            intent.setType("image/jpeg");

            startActivity(intent);

        }

    });

    btn_download_photo.setOnClickListener(new ImageButton.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            DownloadSinglePicTask download = new DownloadSinglePicTask();

            download.setContext(ImageDetailActivity.this);

            download.setAlbunPhotoUrl(clipBoardText);

            Log.w("downloadpic", "ImageDetail albumName:" + albumName);

            download.setPath(
                    extStorageDirectory + "/DCIM/FBBackup/" + name + "/" + Utils.getDirName(albumName) + "/");

            download.execute("test");
        }

    });
}

From source file:es.glasspixel.wlanaudit.fragments.ScanFragment.java

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void copyClipboard(CharSequence text) {
    int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(text);
    } else {/*  w  w w.j a  v  a2 s . com*/
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newPlainText("text label", text);
        clipboard.setPrimaryClip(clip);
    }
    Toast.makeText(getSherlockActivity(), getResources().getString(R.string.key_copy_success),
            Toast.LENGTH_SHORT).show();

}

From source file:com.microsoft.windowsazure.messaging.e2etestapp.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
        startActivity(new Intent(this, NotificationHubsPreferenceActivity.class));
        return true;

    case R.id.menu_run_tests:
        if (ApplicationContext.getNotificationHubEndpoint().trim().equals("")
                || ApplicationContext.getNotificationHubKeyName().trim().equals("")
                || ApplicationContext.getNotificationHubKeyValue().trim().equals("")
                || ApplicationContext.getNotificationHubName().trim().equals("")) {
            startActivity(new Intent(this, NotificationHubsPreferenceActivity.class));
        } else {/* w w w . ja  va2  s .c o  m*/
            runTests();
        }
        return true;

    case R.id.menu_check_all:
        changeCheckAllTests(true);
        return true;

    case R.id.menu_uncheck_all:
        changeCheckAllTests(false);
        return true;

    case R.id.menu_reset:
        refreshTestGroupsAndLog();
        return true;

    case R.id.menu_view_log:
        AlertDialog.Builder logDialogBuilder = new AlertDialog.Builder(this);
        logDialogBuilder.setTitle("Log");

        final WebView webView = new WebView(this);

        String logContent = TextUtils.htmlEncode(mLog.toString()).replace("\n", "<br />");
        String logHtml = "<html><body><pre>" + logContent + "</pre></body></html>";
        webView.loadData(logHtml, "text/html", "utf-8");

        logDialogBuilder.setPositiveButton("Copy", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setText(mLog.toString());
            }
        });

        final String postContent = mLog.toString();

        logDialogBuilder.setNeutralButton("Post data", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            String url = ApplicationContext.getLogPostURL();
                            if (url != null && url.trim() != "") {
                                url = url + "?platform=android";
                                HttpPost post = new HttpPost();
                                post.setEntity(new StringEntity(postContent, "utf-8"));

                                post.setURI(new URI(url));

                                new DefaultHttpClient().execute(post);
                            }
                        } catch (Exception e) {
                            // Wasn't able to post the data. Do nothing
                        }

                        return null;
                    }
                }.execute();
            }
        });

        logDialogBuilder.setView(webView);

        logDialogBuilder.create().show();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.suyonoion.easyviewpagerui.ExpandedViewpagerUI.java

public ExpandedViewpagerUI(Context context, AttributeSet attrs) {
    super(context, attrs);

    List<String> mengisi_Tempat_judul = new ArrayList<>();
    final List<String> kodestringsxml_str = new ArrayList<>();
    final List<String> kodeutama_str = new ArrayList<>();

    for (int i = 1; i <= Jumlah_Page; i++) {
        try {//from   w  ww  .j av  a 2  s . c om
            mengisi_Tempat_judul.add(getResources().getString(setResource("judul_halaman_" + i, "string")));
        }

        catch (Throwable e) {

            if (Jumlah_Page > 25) {
                mengisi_Tempat_judul.add("Judul " + i + " belum ditambahkan di strings.xml");
                AlertDialog.Builder b = new AlertDialog.Builder(getContext());
                final String st = "<LinearLayout android:background=\"@drawable/a3\" android:id=\"@+id/id_halaman_4\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\">\n"
                        + "<TextView android:textSize=\"70sp\" android:layout_gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"3\" android:textColor=\"#ff473eff\"/>\n"
                        + "</LinearLayout>";

                b.setMessage(
                        "Berbahaya Jumlah_Page terlalu banyak lebih dari 25 pages, penambahan kode utama tidak akan ditampilkan...!! Dan"
                                + "Kodeutama->strings.xml->smali belum sinkron (tidak sama). Mengedit 0x3 saja tidak cukup, anda juga perlu mengedit kodeutama dan strings.xml, agar sama. \n \n"
                                + "Jika anda telah mengubah/mengedit/menambah/menghapus Jumlah_Page = 3 (0x3) menjadi Jumlah_Page = "
                                + Jumlah_Page
                                + ", kodeutama, dan strings.xml maka, \n \n Tolong cek dan edit kembali kode utama di expanded anda dan strings.xml di value , sesuaikan dengan jumlah page yaitu "
                                + Jumlah_Page
                                + " dalam smali. dan tambahkan ini sejumlah pages yang anda mau :\n \n" + st
                                + "\n\n" + "sesuaikan dengan id_halaman");
                b.setCancelable(true);
                b.setNeutralButton("Copy to Clipboard", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getContext()
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboard.setText(st);
                            Toast.makeText(getContext(), "Text Telah Ter-Copy ke Clipboard", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getContext()
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            android.content.ClipData clip = android.content.ClipData.newPlainText("Clip", st);
                            Toast.makeText(getContext(), "Text Telah Ter-Copy ke Clipboard", Toast.LENGTH_SHORT)
                                    .show();
                            clipboard.setPrimaryClip(clip);
                        }
                        dialog.dismiss();
                    }
                });
                b.setTitle("Pesan Saya...!!!");
                AlertDialog ad = b.create();
                ad.show();
            } else {
                mengisi_Tempat_judul.add("Judul " + i + " belum ditambahkan di strings.xml");
                AlertDialog.Builder b = new AlertDialog.Builder(getContext());
                kodeutama_str.add(
                        "<LinearLayout android:background=\"@drawable/a3\" android:id=\"@+id/id_halaman_" + i
                                + "\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\">\n"
                                + " <TextView android:textSize=\"70sp\" android:layout_gravity=\"center\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\""
                                + i + "\" android:textColor=\"#ff473eff\"/>\n" + "</LinearLayout> \n \n");

                b.setMessage(
                        "Kodeutama->strings.xml->smali belum sinkron (tidak sama). Mengedit 0x3 saja tidak cukup, anda juga perlu mengedit kodeutama dan strings.xml, agar sama. \n \n"
                                + "Jika anda telah mengubah/mengedit/menambah/menghapus Jumlah_Page = 3 (0x3) menjadi Jumlah_Page = "
                                + Jumlah_Page
                                + ", kodeutama, dan strings.xml maka, \n \n Tolong cek dan edit kembali kode utama di expanded anda dan strings.xml di value , sesuaikan dengan jumlah page yaitu "
                                + Jumlah_Page
                                + " dalam smali atau perhatikan kode utama dibawah ini silahkan dicontek dan tambahkan ke expanded:\n \n"
                                + kodeutama_str + "\n \n"
                                + "Copy to Clipboard dan oh iyah Hapus koma(,) kurung buka dan tutup [ ] yah :)");
                b.setCancelable(true);
                b.setNeutralButton("Copy to Clipboard", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getContext()
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            clipboard.setText(kodeutama_str.toString());
                            Toast.makeText(getContext(), "Text Telah Ter-Copy ke Clipboard", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getContext()
                                    .getSystemService(Context.CLIPBOARD_SERVICE);
                            android.content.ClipData clip = android.content.ClipData.newPlainText("Clip",
                                    kodeutama_str.toString());
                            Toast.makeText(getContext(), "Text Telah Ter-Copy ke Clipboard", Toast.LENGTH_SHORT)
                                    .show();
                            clipboard.setPrimaryClip(clip);
                        }
                        dialog.dismiss();
                    }
                });
                b.setTitle("Pesan Saya...!!!");
                AlertDialog ad = b.create();
                ad.show();
            }

        }
    }

    AdapterExpandedViewpagerUI adapter = new AdapterExpandedViewpagerUI(mengisi_Tempat_judul);
    final ViewPager EasyExpandedViewPagerUI = (ViewPager) this.findViewById(setResource("id_viewpager", "id"));
    EasyExpandedViewPagerUI.setPageTransformer(true, new CubeOutTransformer());
    EasyExpandedViewPagerUI.setAdapter(adapter);
    EasyExpandedViewPagerUI.setOffscreenPageLimit(Jumlah_Page);
    if (EasyExpandedViewPagerUI.getWidth() > 0) {
        Bitmap image = JadikanBlur.blur(EasyExpandedViewPagerUI);
        EasyExpandedViewPagerUI.setBackgroundDrawable(new BitmapDrawable(getContext().getResources(), image));
    } else {
        EasyExpandedViewPagerUI.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Bitmap image = JadikanBlur.blur(EasyExpandedViewPagerUI);
                        EasyExpandedViewPagerUI
                                .setBackgroundDrawable(new BitmapDrawable(getContext().getResources(), image));
                    }
                });
    }

    adapter.notifyDataSetChanged();
}

From source file:net.vivekiyer.GAL.CorporateContactRecordFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    // Get the selected item from the listview adapter
    final KeyValuePair kvp = m_adapter.getItem(info.position);

    switch (item.getItemId()) {
    case MENU_ID_CALL:
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" //$NON-NLS-1$
                + kvp.getValue()));// ww  w .j av  a  2s. c  o m
        startActivity(intent);
        break;
    case MENU_ID_SMS:
        intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" //$NON-NLS-1$
                + kvp.getValue()));
        startActivity(intent);
        break;
    case MENU_ID_COPY_TO_CLIPBOARD:
        final ClipboardManager clipboard = (ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(kvp.getValue());
        Toast.makeText(this.getActivity(), getString(R.string.text_copied_to_clipboard), Toast.LENGTH_SHORT)
                .show();
        break;
    case MENU_ID_EDIT_BEFORE_CALL:
        intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" //$NON-NLS-1$
                + kvp.getValue()));
        startActivity(intent);
        break;
    case MENU_ID_EMAIL:
        intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain"); //$NON-NLS-1$
        intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { kvp.getValue() });
        startActivity(Intent.createChooser(intent, getString(R.string.send_mail)));
        break;
    default:
        return super.onContextItemSelected(item);
    }
    return true;
}

From source file:com.pentacog.mctracker.MCServerTrackerActivity.java

/**
 * @see android.app.Activity#onContextItemSelected(MenuItem item)
 */// w w  w  .  jav  a 2s. c o  m
@Override
public boolean onContextItemSelected(MenuItem item) {
    final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch (item.getItemId()) {
    case R.id.context_copy:
        Server server = serverList.getItem(info.position);
        String address = server.address.toString() + ":" + server.port;
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        clipboard.setText(address);
        Toast.makeText(this, address + " Copied", Toast.LENGTH_SHORT).show();
        return true;
    case R.id.context_delete:
        deleteServer(info.position);
        return true;
    case R.id.context_edit:
        editServer(info.position);
        return true;
    case 124:
        Server s = serverList.getItem(info.position);
        s.favorite = !s.favorite;
        serverList.sort();
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

From source file:com.microsoft.office365.msgraphsnippetapp.SnippetDetailFragment.java

private void clipboard(TextView tv) {
    // which view are we copying to the clipboard?
    int which;/*from  w  w w .  ja  va 2 s  . c  o  m*/

    switch (tv.getId()) {
    case txt_request_url: // the url field
        which = req_url;
        break;

    case txt_response_headers: // the display headers
        which = response_headers;
        break;

    case txt_response_body: // the response body
        which = response_body;
        break;

    default:
        which = UNSET; // don't assign a prefix
    }

    // if we know which view we're copying, prefix it with useful info
    String what = which == UNSET ? "" : getString(which) + " ";

    // concat the clipboard data to this String
    what += getString(clippy);

    // inform the user that data was added to the clipboard
    Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show();

    // depending on our API, do it one way or another...
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        // old way
        ClipboardManager clipboardManager = (ClipboardManager) getActivity()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setText(tv.getText());
    } else {
        clipboard11(tv);
    }
}

From source file:com.wordpress.ebc81.rtl_ais_android.StreamActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stream);
    prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

    terminal = (TextView) findViewById(R.id.terminal);
    scroll = (ScrollView) findViewById(R.id.ScrollArea);
    arguments = (EditText) findViewById(R.id.commandline);

    String argperf = prefs.getString(CMD_LINE_TEXT_PREF, arguments.getText().toString());
    arguments.setText(argperf);//from   w w  w . j a va2s  .co m

    terminal.setText(LogRtlAis.getFullLog());

    ((Button) findViewById(R.id.enable_gui)).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            findViewById(R.id.statusmsg).setVisibility(View.GONE);
            findViewById(R.id.gui).setVisibility(View.VISIBLE);
        }
    });

    (forceroot = (CheckBox) findViewById(R.id.forceRoot))
            .setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    final SharedPreferences.Editor editor = prefs.edit();

                    editor.putBoolean(DISABLE_JAVA_FIX_PREF, isChecked);

                    editor.commit();
                }
            });
    forceroot.setChecked(prefs.getBoolean(DISABLE_JAVA_FIX_PREF, false));

    (onoff = (ToggleButton) findViewById(R.id.onoff)).setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View v) {
            onoff.setChecked(false);
            LogRtlAis.clear();
            String argumentStr = arguments.getText().toString();
            startActivityForResult(
                    new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                            getString(R.string.intent_filter_schema) + "://" + arguments.getText().toString())),
                    START_REQ_CODE);
            if (!argumentStr.isEmpty()) {
                final SharedPreferences.Editor editor = prefs.edit();
                editor.putString(CMD_LINE_TEXT_PREF, argumentStr);
                editor.commit();
            }
        }
    });

    ((Button) findViewById(R.id.bt_default)).setOnClickListener(new Button.OnClickListener() {

        //@SuppressWarnings("deprecation")
        //@SuppressLint("NewApi")
        @Override
        public void onClick(View v) {

            arguments.setText(getString(R.string.default_args));
        }
    });

    ((Button) findViewById(R.id.stop)).setOnClickListener(new Button.OnClickListener() {

        //@SuppressWarnings("deprecation")
        //@SuppressLint("NewApi")
        @Override
        public void onClick(View v) {

            startActivityForResult(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(getString(R.string.intent_filter_schema) + "://-exit")), START_REQ_CODE);
        }
    });

    ((Button) findViewById(R.id.copybutton)).setOnClickListener(new Button.OnClickListener() {

        //@SuppressWarnings("deprecation")
        //@SuppressLint("NewApi")
        @Override
        public void onClick(View v) {
            final String textToClip = terminal.getText().toString();
            int sdk = android.os.Build.VERSION.SDK_INT;
            if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                        Context.CLIPBOARD_SERVICE);
                clipboard.setText(textToClip);
            } else {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                        Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("text label", textToClip);
                clipboard.setPrimaryClip(clip);
            }
            Toast.makeText(getApplicationContext(), R.string.copied_to_clip, Toast.LENGTH_LONG).show();
        }
    });

    ((Button) findViewById(R.id.clearbutton)).setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogRtlAis.clear();
        }
    });

    ((Button) findViewById(R.id.help)).setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(dialogs.DIAG_ABOUT);
        }
    });

    ((Button) findViewById(R.id.license)).setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(dialogs.DIAG_LICENSE);
        }
    });
}

From source file:com.codeskraps.sbrowser.home.SBrowserActivity.java

@SuppressLint("NewApi")
@Override/*from w ww .  ja v  a 2 s . c o m*/
public boolean onContextItemSelected(MenuItem item) {
    Log.v(TAG, "onContextItemSelected");

    WebView.HitTestResult result = webView.getHitTestResult();
    Log.d(TAG, "result: " + result.getExtra());
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);

    switch (item.getItemId()) {
    case R.id.itemSaveImage:
    case R.id.itemSaveLink:

        try {
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Request request = new Request(Uri.parse(result.getExtra()));
            dm.enqueue(request);
        } catch (Exception e) {
            Toast.makeText(this, "sBrowser - Error saving...", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Erro Downloading: " + e);
        }
        break;

    case R.id.itemCopyLink:

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            clipboard.setText(result.getExtra());
        } else {
            android.content.ClipboardManager newClipboard = (android.content.ClipboardManager) getSystemService(
                    CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("label", result.getExtra());
            newClipboard.setPrimaryClip(clip);
        }

        break;

    case R.id.itemShareLink:

        try {
            sharingIntent.setType("text/html");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, result.getExtra());
            startActivity(Intent.createChooser(sharingIntent, "Share using..."));
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "Erro Sharing link: " + e);
        }

        break;

    case R.id.itemShareImage:

        try {
            sharingIntent.setType("image/*");
            sharingIntent.putExtra(Intent.EXTRA_STREAM, result.getExtra());
            startActivity(Intent.createChooser(sharingIntent, "Share image using..."));
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "Erro Sharing Image: " + e);
        }

        break;
    }

    return super.onContextItemSelected(item);
}

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://from   www  .ja 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;
    }
}