Dealing with deprecated android.text.ClipboardManager

巧了我就是萌 提交于 2019-12-03 17:31:00

问题


android.text.ClipboardManager was deprecated since API level 11, and replaced with android.content.ClipboardManager (source).

How do I write code that supports both cases? Importing android.content.ClipboardManager and using that works in 11+ but force closes in 10. Changing the import to android.text.ClipboardManager throws a bunch of deprecation warnings in 11+.

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


回答1:


I ended up just using the old way (android.text.ClipboardManager and the code from this answer), along with a couple @SuppressWarnings("deprecation") annotations.




回答2:


Explicitly:

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

Since this has to keep working on older devices, it is likely that the deprecated code will not be removed from Android.




回答3:


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");
}



回答4:


If you are still supporting < 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);


来源:https://stackoverflow.com/questions/8056838/dealing-with-deprecated-android-text-clipboardmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!