Example usage for android.content ClipData newPlainText

List of usage examples for android.content ClipData newPlainText

Introduction

In this page you can find the example usage for android.content ClipData newPlainText.

Prototype

static public ClipData newPlainText(CharSequence label, CharSequence text) 

Source Link

Document

Create a new ClipData holding data of the type ClipDescription#MIMETYPE_TEXT_PLAIN .

Usage

From source file:org.sufficientlysecure.keychain.ui.ViewKeyAdvShareFragment.java

private void shareKey(boolean toClipboard) {
    Activity activity = getActivity();/* ww  w.  ja v a 2 s  . co m*/
    if (activity == null || mFingerprint == null) {
        return;
    }
    ProviderHelper providerHelper = new ProviderHelper(activity);

    try {
        String content = providerHelper
                .getKeyRingAsArmoredString(KeychainContract.KeyRingData.buildPublicKeyRingUri(mDataUri));

        if (toClipboard) {
            ClipboardManager clipMan = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipMan == null) {
                Notify.create(activity, R.string.error_clipboard_copy, Style.ERROR);
                return;
            }

            ClipData clip = ClipData.newPlainText(Constants.CLIPBOARD_LABEL, content);
            clipMan.setPrimaryClip(clip);

            Notify.create(activity, R.string.key_copied_to_clipboard, Notify.Style.OK).show();
            return;
        }

        // let user choose application
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType(Constants.MIME_TYPE_KEYS);

        // NOTE: Don't use Intent.EXTRA_TEXT to send the key
        // better send it via a Uri!
        // example: Bluetooth Share will convert text/plain sent via Intent.EXTRA_TEXT to HTML
        try {
            TemporaryFileProvider shareFileProv = new TemporaryFileProvider();

            String filename = KeyFormattingUtils.convertFingerprintToHex(mFingerprint);
            OpenPgpUtils.UserId mainUserId = KeyRing.splitUserId(mUserId);
            if (mainUserId.name != null) {
                filename = mainUserId.name;
            }
            Uri contentUri = TemporaryFileProvider.createFile(activity,
                    filename + Constants.FILE_EXTENSION_ASC);

            BufferedWriter contentWriter = new BufferedWriter(new OutputStreamWriter(
                    new ParcelFileDescriptor.AutoCloseOutputStream(shareFileProv.openFile(contentUri, "w"))));
            contentWriter.write(content);
            contentWriter.close();

            sendIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        } catch (FileNotFoundException e) {
            Log.e(Constants.TAG, "Error creating temporary key share file!", e);
            // no need for a snackbar because one sharing option doesn't work
            // Notify.create(getActivity(), R.string.error_temp_file, Notify.Style.ERROR).show();
        }

        String title = getString(R.string.title_share_key);
        Intent shareChooser = Intent.createChooser(sendIntent, title);

        startActivity(shareChooser);
    } catch (PgpGeneralException | IOException e) {
        Log.e(Constants.TAG, "error processing key!", e);
        Notify.create(activity, R.string.error_key_processing, Notify.Style.ERROR).show();
    } catch (ProviderHelper.NotFoundException e) {
        Log.e(Constants.TAG, "key not found!", e);
        Notify.create(activity, R.string.error_key_not_found, Notify.Style.ERROR).show();
    }
}

From source file:com.flym.dennikn.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;/*w  w  w.  ja  va 2s  . co  m*/

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:arun.com.chameleonskinforkwlp.MainActivity.java

public void onFormulaClicked(View view) {
    if (view instanceof TextView) {
        TextView textView = (TextView) view;
        final ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        final CharSequence textToCopy = textView.getText();
        final ClipData clip = ClipData.newPlainText("formula", textToCopy);
        Snackbar.make(binding.coordinatorLayout, String.format(getString(R.string.copied_alert), textToCopy),
                Snackbar.LENGTH_SHORT).show();
        clipboard.setPrimaryClip(clip);/*w w w . j a  v a2  s.co m*/
    }
}

From source file:com.viktorrudometkin.burramys.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from   ww  w  .  j  ava  2  s.  co m

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            UiUtils.showMessage(getActivity(), R.string.copied_clipboard);
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:com.carlrice.reader.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  www.  jav a 2  s. co  m

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = Application.context().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = Application.context().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:net.etuldan.sparss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//w  w  w  . j  a  v  a  2s . co  m

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPreferFullText = true;
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSwipeProgress();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.github.dfa.diaspora_android.ui.ContextMenuWebView.java

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            HitTestResult result = getHitTestResult();
            String url = result.getExtra();
            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                boolean writeToStoragePermitted = true;
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    int hasWRITE_EXTERNAL_STORAGE = parentActivity
                            .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                        writeToStoragePermitted = false;
                        if (!parentActivity.shouldShowRequestPermissionRationale(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                    .setPositiveButton(context.getText(android.R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (android.os.Build.VERSION.SDK_INT >= 23)
                                                        parentActivity.requestPermissions(new String[] {
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                }
                                            })
                                    .setNegativeButton(context.getText(android.R.string.no), null).show();
                        }/*  w ww  .  j  a v  a  2  s  .c  o  m*/
                        parentActivity.requestPermissions(
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                    }
                }
                if (writeToStoragePermitted) {
                    if (url != null) {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        File destinationFile = new File(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
                        Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location)
                                + " " + destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    }
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {
                    boolean writeToStoragePermitted = true;
                    if (android.os.Build.VERSION.SDK_INT >= 23) {
                        int hasWRITE_EXTERNAL_STORAGE = parentActivity
                                .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                            writeToStoragePermitted = false;
                            if (!parentActivity.shouldShowRequestPermissionRationale(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                        .setPositiveButton(context.getText(android.R.string.yes),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        if (android.os.Build.VERSION.SDK_INT >= 23)
                                                            parentActivity.requestPermissions(new String[] {
                                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                    MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                    }
                                                })
                                        .setNegativeButton(context.getText(android.R.string.no), null).show();
                            } else {
                                parentActivity.requestPermissions(
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                            }
                        }
                    }
                    if (writeToStoragePermitted) {
                        final Uri local = Uri.parse(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        new ImageDownloadTask(null, local.getPath()) {
                            @Override
                            protected void onPostExecute(Bitmap result) {
                                Uri myUri = Uri.fromFile(new File(local.getPath()));
                                Intent sharingIntent = new Intent();
                                sharingIntent.setAction(Intent.ACTION_SEND);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
                                sharingIntent.setType("image/png");
                                sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                context.startActivity(Intent.createChooser(sharingIntent,
                                        getResources().getString(R.string.action_share_dotdotdot)));
                            }
                        }.execute(url);
                    }
                } else {
                    Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
                }

                break;

            case ID_IMAGE_EXTERNAL_BROWSER:
                if (url != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                }
                break;

            //Copy url to clipboard
            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) context
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            //Try to share link to other apps
            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    context.startActivity(Intent.createChooser(sendIntent,
                            getResources().getText(R.string.context_menu_share_link)));
                }
                break;
            }
            return true;
        }
    };

    //Build context menu
    if (result.getType() == HitTestResult.IMAGE_TYPE
            || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        // Menu options for an image.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0,
                context.getString(R.string.context_menu_open_external_browser))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == HitTestResult.ANCHOR_TYPE
            || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
        // Menu options for a hyperlink.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:com.github.dfa.diaspora_android.web.ContextMenuWebView.java

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            HitTestResult result = getHitTestResult();
            String url = result.getExtra();
            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                boolean writeToStoragePermitted = true;
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    int hasWRITE_EXTERNAL_STORAGE = parentActivity
                            .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                        writeToStoragePermitted = false;
                        if (!parentActivity.shouldShowRequestPermissionRationale(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                    .setPositiveButton(context.getText(android.R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (android.os.Build.VERSION.SDK_INT >= 23)
                                                        parentActivity.requestPermissions(new String[] {
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                }
                                            })
                                    .setNegativeButton(context.getText(android.R.string.no), null).show();
                        }/* w w w  . jav a  2s  . c om*/
                        parentActivity.requestPermissions(
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                    }
                }
                if (writeToStoragePermitted) {
                    if (url != null) {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        File destinationFile = new File(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);

                        Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location)
                                + " " + destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    }
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {
                    boolean writeToStoragePermitted = true;
                    if (android.os.Build.VERSION.SDK_INT >= 23) {
                        int hasWRITE_EXTERNAL_STORAGE = parentActivity
                                .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                            writeToStoragePermitted = false;
                            if (!parentActivity.shouldShowRequestPermissionRationale(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                        .setPositiveButton(context.getText(android.R.string.yes),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        if (android.os.Build.VERSION.SDK_INT >= 23)
                                                            parentActivity.requestPermissions(new String[] {
                                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                    MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                    }
                                                })
                                        .setNegativeButton(context.getText(android.R.string.no), null).show();
                            } else {
                                parentActivity.requestPermissions(
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                            }
                        }
                    }
                    if (writeToStoragePermitted) {
                        final Uri local = Uri.parse(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        new ImageDownloadTask(null, local.getPath()) {
                            @Override
                            protected void onPostExecute(Bitmap result) {
                                Uri myUri = Uri.fromFile(new File(local.getPath()));
                                Intent sharingIntent = new Intent();
                                sharingIntent.setAction(Intent.ACTION_SEND);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
                                sharingIntent.setType("image/png");
                                sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                context.startActivity(Intent.createChooser(sharingIntent,
                                        getResources().getString(R.string.action_share_dotdotdot)));
                            }
                        }.execute(url);
                    }
                } else {
                    Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
                }

                break;

            case ID_IMAGE_EXTERNAL_BROWSER:
                if (url != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                }
                break;

            //Copy url to clipboard
            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) context
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            //Try to share link to other apps
            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    context.startActivity(Intent.createChooser(sendIntent,
                            getResources().getText(R.string.context_menu_share_link)));
                }
                break;
            }
            return true;
        }
    };

    //Build context menu
    if (result.getType() == HitTestResult.IMAGE_TYPE
            || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        // Menu options for an image.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0,
                context.getString(R.string.context_menu_open_external_browser))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == HitTestResult.ANCHOR_TYPE
            || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
        // Menu options for a hyperlink.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:net.news.inrss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  ww w .  ja v a  2s. c om

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        Log.d(TAG, "run: manual call of displayEntry(), fullText=false");
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    Log.d(TAG, "onOptionsItemSelected: alreadyMobilized");
                    mPreferFullText = true;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: manual call of displayEntry(), fullText=true");
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    Log.d(TAG, "onOptionsItemSelected: about to load article...");
                    mPreferFullText = false;
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                        Log.d(TAG, "onOptionsItemSelected: cannot load article. no internet connection.");
                    }
                } else {
                    Log.d(TAG, "onOptionsItemSelected: refreshing already in progress");
                }
            }
            mShowFullContentItem.setChecked(mPreferFullText);
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:key.secretkey.crypto.PgpHandler.java

public void copyToClipBoard() {

    if (findViewById(R.id.crypto_password_show) == null)
        return;/*www  .ja  v  a2 s  .  c  o m*/

    if (decodedPassword.isEmpty()) {
        return;
    }

    setTimer();

    ClipData clip = ClipData.newPlainText("pgp_handler_result_pm", decodedPassword);
    clipboard.setPrimaryClip(clip);

    try {
        showToast(this.getResources().getString(R.string.clipboard_beginning_toast_text) + " "
                + Integer.parseInt(settings.getString("general_show_time", "45")) + " "
                + this.getResources().getString(R.string.clipboard_ending_toast_text));
    } catch (NumberFormatException e) {
        showToast(this.getResources().getString(R.string.clipboard_beginning_toast_text) + " 45 "
                + this.getResources().getString(R.string.clipboard_ending_toast_text));
    }
}