clipboard (1)


Clipboard Manager in Android Web View

Inter-workings JavaScript and Java Layer: use Clipboard Manager APIs directly in WebView component of Android library:

// no permission require in your manifest file of Android project

        ...


// start code
@SuppressLint({"SetJavaScriptEnabled","JavascriptInterface"})
public class MainActivity extends Activity {
public WebView webView;
ClipboardManager myClipboard;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main); // source activity_main.xml
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.setWebViewClient(new WebViewClient());
// important set Web Chrome Client
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl(url); //local or remote
}
// final class to add in Web App
final class WebAppInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        WebAppInterface(Context c) {
            mContext = c;
        }
        /**
            Interface to use in web application
        */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@JavascriptInterface
	    public void copyToClipboard(String text) {
	        try {
	        	myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
	        	ClipData myClip;
	        	myClip = ClipData.newPlainText("text", text);
	        	myClipboard.setPrimaryClip(myClip);
	        	Toast.makeText(getApplicationContext(), "Text Copied",Toast.LENGTH_SHORT).show();
	        } catch (Exception e) {
	        	Toast.makeText(getApplicationContext(), "Copy failed: " + e.toString(), Toast.LENGTH_SHORT).show();
	        }
	    }
    }

}
// Now open html file in www folder of you Android project