Working with deprecated android.text.ClipboardManager

android.text.ClipboardManager been deprecated from API level 11 and replaced by android.content.ClipboardManager ( source ).

How to write code that supports both cases? Importing android.content.ClipboardManager and using it works in 11+, but the force closes at 10. Changing the import to android.text.ClipboardManager causes a bunch of warnings about fatigue in 11+.

How can I handle both cases smoothly? What do I need to import?

+7
source share
4 answers

I ended up using the old way (android.text.ClipboardManager and the code for this answer ), as well as a couple of @SuppressWarnings ("deprecation") annotations.

+6
source

Explicit:

  @SuppressWarnings("deprecation") android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(shareViaSMSBody); 

Since this should continue to work with older devices, it is likely that legacy code will not be deleted from Android.

+4
source

Referring to this answer :

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) context .getSystemService(Context.CLIPBOARD_SERVICE); final android.content.ClipData clipData = android.content.ClipData .newPlainText("text label", "text to clip"); clipboardManager.setPrimaryClip(clipData); } else { final android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context .getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setText("text to clip"); } 
+2
source

If you still support <SDK 11 you are doing too much work. Set min to 15 and use this code:

  ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("label for text", "text to copy"); clipboard.setPrimaryClip(clip); 
0
source

All Articles