Android How to - Put String data to Clipboard








Question

We would like to know how to put String data to Clipboard.

Answer

//from   w  ww . j av  a 2  s .  c om
import android.annotation.SuppressLint;
import android.content.Context;

public class Main {

  @SuppressLint("NewApi")
    public static void put (String clipData, Context context){
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { //Android 2.3 and below
      android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
      clipboard.setText(clipData);
    } else { //Android 3.0 and higher
            try {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("pasted data", clipData);
                clipboard.setPrimaryClip(clip);
            } catch (Exception e){
                e.printStackTrace();
            }
    }
  }
}