ClipboardUtil.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * Copyright (C) 2018 Andy Scherzinger
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public
  18. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.owncloud.android.utils;
  21. import android.app.Activity;
  22. import android.content.ClipData;
  23. import android.content.ClipboardManager;
  24. import android.content.Context;
  25. import android.widget.Toast;
  26. import com.owncloud.android.R;
  27. import com.owncloud.android.lib.common.utils.Log_OC;
  28. /**
  29. * Helper implementation to copy a string into the system clipboard.
  30. */
  31. public class ClipboardUtil {
  32. private static final String TAG = ClipboardUtil.class.getName();
  33. private ClipboardUtil() {
  34. }
  35. public static void copyToClipboard(Activity activity, String text) {
  36. copyToClipboard(activity, text, true);
  37. }
  38. public static void copyToClipboard(Activity activity, String text, boolean showToast) {
  39. if (text != null && text.length() > 0) {
  40. try {
  41. ClipData clip = ClipData.newPlainText(
  42. activity.getString(
  43. R.string.clipboard_label, activity.getString(R.string.app_name)),
  44. text
  45. );
  46. ((ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(clip);
  47. if (showToast) {
  48. Toast.makeText(activity, R.string.clipboard_text_copied, Toast.LENGTH_SHORT).show();
  49. }
  50. } catch (Exception e) {
  51. Toast.makeText(activity, R.string.clipboard_unexpected_error, Toast.LENGTH_SHORT).show();
  52. Log_OC.e(TAG, "Exception caught while copying to clipboard", e);
  53. }
  54. } else {
  55. Toast.makeText(activity, R.string.clipboard_no_text_to_copy, Toast.LENGTH_SHORT).show();
  56. }
  57. }
  58. }