Android ClipboardManager- Put or Get

Android ClipboardManager

This is a practical example to teach you how to use the ClipboardManager class. You can use this class to achieve copy/paste functionality in android app.

How to Put String into Clipboard

Here’s how:

public static void putStringToClipboard(@NonNull String content){
        ClipData data = ClipData.newPlainText(null,content);
        sClipboardManager.setPrimaryClip(data);
    }

How to get string from clipboard

here’s how:

public static String getStringFromClipboard(){
        ClipData clipData = sClipboardManager.getPrimaryClip();
        if (clipData != null){
            Log.d(TAG, "getStringFromClipboard: nclipData = " + clipData.toString());
            if (clipData.getItemCount() > 0){
                return clipData.getItemAt(0).getText().toString();
            }
        }
        return "";
    }

Here’s the full class:

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import com.jiangkang.tools.King;

public class ClipboardUtils {

    private static final String TAG = ClipboardUtils.class.getSimpleName();
    private static ClipboardManager sClipboardManager;

    static {
        sClipboardManager = (ClipboardManager) King.getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
    }

    public static void putStringToClipboard(@NonNull String content){
        ClipData data = ClipData.newPlainText(null,content);
        sClipboardManager.setPrimaryClip(data);
    }

    public static String getStringFromClipboard(){
        ClipData clipData = sClipboardManager.getPrimaryClip();
        if (clipData != null){
            Log.d(TAG, "getStringFromClipboard: nclipData = " + clipData.toString());
            if (clipData.getItemCount() > 0){
                return clipData.getItemAt(0).getText().toString();
            }
        }
        return "";
    }

}

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Related Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code