Java Code Examples for android.content.ClipboardManager#hasPrimaryClip()

The following examples show how to use android.content.ClipboardManager#hasPrimaryClip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PopupActivity.java    From ankihelper with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(isFromAndroidQClipboard) {
        if (!Settings.getInstance(MyApplication.getContext()).getMoniteClipboardQ()) {
            return;
        }
        ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        if (cb.hasPrimaryClip()) {
            if (cb.hasText()) {
                String text = cb.getText().toString();
                mTextToProcess = text;
            }
        }
        populateWordSelectBox();
        bigBangLayout.post( new Runnable() {
            @Override
            public void run() {
                setTargetWord();
                if(Utils.containsTranslationField(currentOutputPlan)){
                    asyncTranslate(mTextToProcess);
                }
            }
        });
    }
}
 
Example 2
Source File: ClipboardReceiver.java    From io.appium.settings with Apache License 2.0 6 votes vote down vote up
private String getClipboardText(Context context) {
    final ClipboardManager cm = (ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    if (cm == null) {
        Log.e(TAG, "Cannot get an instance of ClipboardManager");
        return null;
    }
    if (!cm.hasPrimaryClip()) {
        return "";
    }
    final ClipData cd = cm.getPrimaryClip();
    if (cd == null || cd.getItemCount() == 0) {
        return "";
    }
    return charSequenceToString(cd.getItemAt(0).coerceToText(context));
}
 
Example 3
Source File: EditTextPlain.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean onTextContextMenuItem(int id) {
    try {
        if (id == android.R.id.paste) {
            Context context = getContext();
            ClipboardManager cbm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            if (cbm != null && cbm.hasPrimaryClip()) {
                ClipData data = cbm.getPrimaryClip();
                ClipData.Item item = data.getItemAt(0);

                CharSequence text = item.coerceToText(context);
                data = ClipData.newPlainText("coerced_plain_text", text);
                cbm.setPrimaryClip(data);
            }
        }

        return super.onTextContextMenuItem(id);
    } catch (Throwable ex) {
        Log.w(ex);
        return false;
    }
}
 
Example 4
Source File: SelectionPopupController.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public boolean canPasteAsPlainText() {
    // String resource "paste_as_plain_text" only exist in O.
    // Also this is an O feature, we need to make it consistant with TextView.
    if (!BuildInfo.isAtLeastO()) return false;
    if (!mCanEditRichlyForPastePopup) return false;
    ClipboardManager clipMgr =
            (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
    if (!clipMgr.hasPrimaryClip()) return false;

    ClipData clipData = clipMgr.getPrimaryClip();
    ClipDescription description = clipData.getDescription();
    CharSequence text = clipData.getItemAt(0).getText();
    boolean isPlainType = description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
    // On Android, Spanned could be copied to Clipboard as plain_text MIME type, but in some
    // cases, Spanned could have text format, we need to show "paste as plain text" when
    // that happens.
    if (isPlainType && (text instanceof Spanned)) {
        Spanned spanned = (Spanned) text;
        if (hasStyleSpan(spanned)) return true;
    }
    return description.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
}
 
Example 5
Source File: CustomThemeListingActivity.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void importTheme() {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboard != null) {
        // If it does contain data, decide if you can handle the data.
        if (!clipboard.hasPrimaryClip()) {
            Snackbar.make(coordinatorLayout, R.string.no_data_in_clipboard, Snackbar.LENGTH_SHORT).show();
        } else if (clipboard.getPrimaryClipDescription() != null &&
                !clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN)) {
            // since the clipboard has data but it is not plain text
            Snackbar.make(coordinatorLayout, R.string.no_data_in_clipboard, Snackbar.LENGTH_SHORT).show();
        } else if (clipboard.getPrimaryClip() != null) {
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            String json = item.getText().toString();
            try {
                CustomTheme customTheme = new Gson().fromJson(json, CustomTheme.class);
                checkDuplicateAndImportTheme(customTheme, true);
            } catch (JsonSyntaxException e) {
                Snackbar.make(coordinatorLayout, R.string.parse_theme_failed, Snackbar.LENGTH_SHORT).show();
            }
        }
    }
}
 
Example 6
Source File: NMBEditText.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onTextContextMenuItem(int id) {
    // Get text in clipboard
    ClipboardManager cbm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
    if (cbm.hasPrimaryClip()) {
        ClipData clipData = cbm.getPrimaryClip();
        if (clipData.getItemCount() > 0) {
            // Convert to plain text
            CharSequence text = clipData.getItemAt(0).getText();
            if (text != null) {
                cbm.setPrimaryClip(ClipData.newPlainText(null, text.toString()));
            }
        }
    }

    return super.onTextContextMenuItem(id);
}
 
Example 7
Source File: CBWatcherService.java    From ankihelper with GNU General Public License v3.0 6 votes vote down vote up
private void performClipboardCheck() {
    Log.d("clip", "clip_changed");
    if (!Settings.getInstance(MyApplication.getContext()).getMoniteClipboardQ()) {
        return;
    }
    ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    if (cb.hasPrimaryClip()) {
        if (cb.hasText()) {
            String text = cb.getText().toString();
            if (/*isEnglish(text)*/true) {
                long[] vibList = new long[1];
                vibList[0] = 10L;
                Intent intent = new Intent(getApplicationContext(), PopupActivity.class);
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                //intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                intent.putExtra(Intent.EXTRA_TEXT, text);
                startActivity(intent);
            }
        }
    }
}
 
Example 8
Source File: MainActivity.java    From FileTransfer with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboard != null && clipboard.hasPrimaryClip() && clipboard.getPrimaryClip() != null) {
        ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
        if (item != null && item.getText() != null && item.getText().length() > 0 && !item.getText().equals(mAlreadyWrited)) {
            File file = new File(Constants.DIR, "clipboard_" + String.valueOf(System.currentTimeMillis()) + ".txt");
            try {
                FileUtils.writeByteArrayToFile(file, item.getText().toString().getBytes(), false);
                Toast.makeText(this, "已把剪切板中内容写入到该文件中", Toast.LENGTH_SHORT).show();
                RxBus.get().post(Constants.RxBusEventType.LOAD_BOOK_LIST, 0);
                mAlreadyWrited = item.getText().toString();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "文件写入失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
 
Example 9
Source File: MainContentProviderBase.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
public static boolean hasSelectionInClipboard(ClipboardManager clipboard)
{
    if(!clipboard.hasPrimaryClip())
    {
        Logger.debug("hasSelectionInClipboard: clipboard doesn't have a primary clip");
        return false;
    }
    ClipData clip = clipboard.getPrimaryClip();
    if(clip!=null)
    {
        if(GlobalConfig.isDebug())
            Logger.debug(String.format("hasSelectionInClipboard: clip = %s", clip));
        return clip.getItemCount() > 0 && MainContentProvider.isClipboardUri(clip.getItemAt(0).getUri());
    }

    Logger.debug("hasSelectionInClipboard: clip = null");
    return false;
}
 
Example 10
Source File: PlansManagerActivity.java    From ankihelper with GNU General Public License v3.0 5 votes vote down vote up
private void importPlans() {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    if(clipboard.hasPrimaryClip()){
        if(clipboard.getText()!=null){
            String plansString = clipboard.getText().toString();
            processPlanString(plansString);
        }
    }else{
        Toast.makeText(this, "剪贴板为空!", Toast.LENGTH_SHORT).show();
    }
}
 
Example 11
Source File: ClipboardUtils.java    From FreezeYou with Apache License 2.0 5 votes vote down vote up
public static CharSequence getClipboardItemText(Context context) {
    ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    if (cm == null || !cm.hasPrimaryClip()) {
        return "";
    }
    ClipData clip = cm.getPrimaryClip();
    if (clip == null || clip.getItemCount() <= 0) {
        return "";
    }
    return clip.getItemAt(0).getText();
}
 
Example 12
Source File: Helper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
static public String getClipBoardText(Context context) {
    final ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    try {
        if (clipboardManager.hasPrimaryClip()
                && clipboardManager.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            final ClipData.Item item = clipboardManager.getPrimaryClip().getItemAt(0);
            return item.getText().toString();
        }
    } catch (NullPointerException ex) {
        // if we have don't find a text in the clipboard
        return null;
    }
    return null;
}
 
Example 13
Source File: BaseTools.java    From CloudReader with Apache License 2.0 5 votes vote down vote up
/**
 * 获取系统剪切板内容
 */
public static String getClipContent() {
    ClipboardManager manager = (ClipboardManager) App.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
    if (manager != null && manager.getPrimaryClip() != null) {
        if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {
            CharSequence addedText = manager.getPrimaryClip().getItemAt(0).getText();
            String addedTextString = String.valueOf(addedText);
            if (!TextUtils.isEmpty(addedTextString)) {
                return StringFormatUtil.formatUrl(String.valueOf(addedText));
            }
        }
    }
    return "";
}
 
Example 14
Source File: ActivityServiceUtils.java    From HgLauncher with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Pastes the first clip item containing the mimetype text.
 *
 * @param activity Activity where CLIPBOARD_SERVICE can be fetched.
 *
 * @return CharSequence text from clipboard, empty if there isn't any.
 */
public static CharSequence pasteFromClipboard(Activity activity) {
    ClipboardManager clipboardManager = (ClipboardManager) activity
            .getSystemService(Context.CLIPBOARD_SERVICE);

    if (clipboardManager != null && clipboardManager.hasPrimaryClip()
            && clipboardManager.getPrimaryClipDescription()
                               .hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
        return clipboardManager.getPrimaryClip().getItemAt(0).getText();
    } else {
        return "";
    }
}
 
Example 15
Source File: Utils.java    From ForPDA with GNU General Public License v3.0 5 votes vote down vote up
public static String readFromClipboard() {
    ClipboardManager clipboard = (ClipboardManager) App.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboard.hasPrimaryClip()) {
        android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
        android.content.ClipData data = clipboard.getPrimaryClip();
        if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
            return String.valueOf(data.getItemAt(0).getText());
    }
    return null;
}
 
Example 16
Source File: Util.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static @Nullable String readTextFromClipboard(@NonNull Context context) {
  {
    ClipboardManager clipboardManager = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);

    if (clipboardManager.hasPrimaryClip() && clipboardManager.getPrimaryClip().getItemCount() > 0) {
      return clipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
    } else {
      return null;
    }
  }
}
 
Example 17
Source File: WebViewActivity.java    From movienow with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void processLogic(Bundle savedInstanceState) {
    if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
    }
    //初始化监听剪贴板
    final ClipboardManager manager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    hasPrimaryClip = new ClipboardManager.OnPrimaryClipChangedListener() {
        @Override
        public void onPrimaryClipChanged() {
            long now = System.currentTimeMillis();
            if (now - previousTime < 5000) {
                return;
            }
            previousTime = now;
            if (manager == null || !manager.hasPrimaryClip()) {
                return;
            }
            //如果是文本信息
            if (manager.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)
                    || manager.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML)) {
                ClipData cdText = manager.getPrimaryClip();
                ClipData.Item item = cdText.getItemAt(0);
                //此处是TEXT文本信息
                if (item.getText() != null) {
                    final String t = item.getText().toString();
                    Snackbar.make(webViewT, "剪贴板被使用,是否撤销内容", Snackbar.LENGTH_LONG)
                            .setAction("撤销", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Helper.copyToClipboard(getContext(), text);
                                }
                            }).addCallback(new Snackbar.Callback() {
                        @Override
                        public void onDismissed(Snackbar transientBottomBar, int event) {
                            text = t;
                            super.onDismissed(transientBottomBar, event);
                        }
                    }).show();
                }
            }
        }
    };
    if (manager != null) {
        manager.addPrimaryClipChangedListener(hasPrimaryClip);
    }
}
 
Example 18
Source File: SelectActionModeCallback.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private boolean canPaste() {
    ClipboardManager clipMgr = (ClipboardManager)
            getContext().getSystemService(Context.CLIPBOARD_SERVICE);
    return clipMgr.hasPrimaryClip();
}
 
Example 19
Source File: AppManager.java    From ShadowsocksRR with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onMenuItemClick(MenuItem item) {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    String proxiedAppString = null;
    switch (item.getItemId()) {
        case R.id.action_apply_all:
            List<Profile> profiles = app.profileManager.getAllProfiles();
            if (profiles != null) {
                proxiedAppString = profile.individual;
                for (Profile p : profiles) {
                    p.individual = proxiedAppString;
                    app.profileManager.updateProfile(p);
                }
                ToastUtils.showShort(R.string.action_apply_all);
            } else {
                ToastUtils.showShort(R.string.action_export_err);
            }
            return true;
        case R.id.action_export:
            boolean bypass = profile.bypass;
            proxiedAppString = profile.individual;
            ClipData clip = ClipData.newPlainText(Constants.Key.individual, bypass + "\n" + proxiedAppString);
            if (clipboard != null) {
                clipboard.setPrimaryClip(clip);
                ToastUtils.showShort(R.string.action_export_msg);
            }
            return true;
        case R.id.action_import:
            if (clipboard != null && clipboard.hasPrimaryClip()) {
                CharSequence proxiedAppSequence = clipboard.getPrimaryClip().getItemAt(0).getText();
                if (proxiedAppSequence != null) {
                    proxiedAppString = proxiedAppSequence.toString();
                    if (!TextUtils.isEmpty(proxiedAppString)) {
                        int i = proxiedAppString.indexOf('\n');
                        try {
                            String enabled;
                            String apps;
                            if (i < 0) {
                                enabled = proxiedAppString;
                                apps = "";
                            } else {
                                enabled = proxiedAppString.substring(0, i);
                                apps = proxiedAppString.substring(i + 1);
                            }

                            bypassSwitch.setChecked(Boolean.parseBoolean(enabled));
                            profile.individual = apps;
                            app.profileManager.updateProfile(profile);
                            ToastUtils.showShort(R.string.action_import_msg);
                            appListView.setVisibility(View.GONE);
                            loadingView.setVisibility(View.VISIBLE);
                            initProxiedApps(apps);
                            reloadApps();
                            return true;
                        } catch (Exception e) {
                            ToastUtils.showShort(R.string.action_import_err);
                        }
                    }
                }
            }
            ToastUtils.showShort(R.string.action_import_err);
            return false;
        default:
            break;
    }
    return false;
}
 
Example 20
Source File: CRPreferenceActivity.java    From comfortreader with GNU General Public License v3.0 3 votes vote down vote up
public String readFromClipboard() {

        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        String pasteData = "";


        if (!(clipboard.hasPrimaryClip())) {
            //disabled

            Log.i("Options", "has primaty clip" + pasteData);


        } else if (clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_HTML) || clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN)) {

            Log.i("Options", "plain text");



            // This enables the paste menu item, since the clipboard contains plain text.
            //enabled
            //copy stuff
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);

// Gets the clipboard as text.
            pasteData = item.getText().toString();

        }


        //      Log.i("Reading from Clipboard", pasteData);

        Log.i("Options", "THIS IS" + pasteData);


        return pasteData;
    }