copy To Clipboard for api version 11 and 10 - Android android.content

Android examples for android.content:Clipboard

Description

copy To Clipboard for api version 11 and 10

Demo Code

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;

public class Main{

    public static void copyToClipboard(@NonNull Context context,
            @NonNull String toCopy) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            copyToClipboard11AndLater(context, toCopy);
        } else {/*from w  w  w.  j a va 2 s  .com*/
            copyToClipboard10AndBefore(context, toCopy);
        }
    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private static void copyToClipboard11AndLater(@NonNull Context context,
            @NonNull String toCopy) {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("Copied Text", toCopy);
        clipboard.setPrimaryClip(clip);
    }
    private static void copyToClipboard10AndBefore(
            @NonNull Context context, @NonNull String toCopy) {
        @SuppressWarnings("deprecation")
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(toCopy);
    }

}

Related Tutorials