ClipboardUtil.kt 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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.text.TextUtils
  26. import android.widget.Toast
  27. import com.owncloud.android.R
  28. import com.owncloud.android.lib.common.utils.Log_OC
  29. /**
  30. * Helper implementation to copy a string into the system clipboard.
  31. */
  32. object ClipboardUtil {
  33. private val TAG = ClipboardUtil::class.java.name
  34. @JvmStatic
  35. @JvmOverloads
  36. @Suppress("TooGenericExceptionCaught")
  37. fun copyToClipboard(activity: Activity, text: String?, showToast: Boolean = true) {
  38. if (!TextUtils.isEmpty(text)) {
  39. try {
  40. val clip = ClipData.newPlainText(
  41. activity.getString(
  42. R.string.clipboard_label,
  43. activity.getString(R.string.app_name)
  44. ),
  45. text
  46. )
  47. (activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(clip)
  48. if (showToast) {
  49. Toast.makeText(activity, R.string.clipboard_text_copied, Toast.LENGTH_SHORT).show()
  50. }
  51. } catch (e: Exception) {
  52. Toast.makeText(activity, R.string.clipboard_unexpected_error, Toast.LENGTH_SHORT).show()
  53. Log_OC.e(TAG, "Exception caught while copying to clipboard", e)
  54. }
  55. } else {
  56. Toast.makeText(activity, R.string.clipboard_no_text_to_copy, Toast.LENGTH_SHORT).show()
  57. }
  58. }
  59. }