set Text as Primary Clip in Clipboard - Android Android OS

Android examples for Android OS:Clipboard

Description

set Text as Primary Clip in Clipboard

Demo Code


//package com.java2s;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;

public class Main {
    private static ClipboardManager mClipboardManager;
    private static android.content.ClipboardManager mNewCliboardManager;

    public static void setText(Context context, CharSequence text) {
        if (isNew()) {
            instance(context);/*from  w ww  . j a v  a2  s. c om*/
            // Creates a new text clip to put on the clipboard
            ClipData clip = ClipData.newPlainText("simple text", text);

            // Set the clipboard's primary clip.
            mNewCliboardManager.setPrimaryClip(clip);
        } else {
            instance(context);
            mClipboardManager.setText(text);
        }
    }

    private static boolean isNew() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    private static void instance(Context context) {
        if (isNew()) {
            if (mNewCliboardManager == null)
                mNewCliboardManager = (android.content.ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
        } else {
            if (mClipboardManager == null)
                mClipboardManager = (ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
        }
    }
}

Related Tutorials