get Clipboard Text by API version - Android android.content

Android examples for android.content:ClipboardManager

Description

get Clipboard Text by API version

Demo Code

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.View;
import android.widget.ListView;

public class Main{

    /**/*from w  w  w.  j  a  v a 2 s.c  o  m*/
     * Get text content of clipboard. Compatibility variant
     *
     * @param ctx context
     * @return string result or null if not found anything
     */
    public static String getClipboardText(Context ctx) {
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            return getClipboardTextLegacy(ctx);
        } else {
            return getClipboardTextNew(ctx);
        }

    }
    private static String getClipboardTextNew(Context ctx) {
        String txt = null;
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ctx
                .getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null) {
            if (clipboard.hasPrimaryClip()) {
                txt = clipboard.getPrimaryClip().getItemAt(0).getText()
                        .toString();
            }
        }
        return txt;
    }
    private static String getClipboardTextLegacy(Context ctx) {
        String txt = null;
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ctx
                .getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null) {
            txt = clipboard.getText().toString();
        }
        return txt;
    }

}

Related Tutorials