Search code examples
androidandroid-alertdialogclipboardandroid-11clipboardmanager

Android development: How to listen to clipboard changes outside of an APP on Android 11?


I have a personal APP primarily developed for Android 9 that listens to clipboard changes and prompt a window on top of wherever I copy a URL. The implementation is as below:

ClipboardManager.OnPrimaryClipChangedListener listener = () -> {
    Log.d("APP", "Detected clipboard change.");

    if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {

        CharSequence addedText = manager.getPrimaryClip().getItemAt(0).getText();

        if (addedText != null) {
            Log.d("APP", "copied text: " + addedText);
            if ( addedText.toString().startsWith("http") ) {

                Date dNow = new Date( );
                SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");

                AlertDialog newDialog = new AlertDialog.Builder(MainActivity.this)
                        .setMessage("Detected link, deal with it?")
                        .setPositiveButton("OK", (dialog, which) -> {
                            Intent it = new Intent(Intent.ACTION_SEND);
                            it.putExtra(Intent.EXTRA_TEXT, addedText);
                            it.setClass(MainActivity.this, MainActivity.class);
                            startActivity(it);

                            finish();
                        })
                        .setNegativeButton("No", null)
                        .setCancelable(true)
                        .create();
                newDialog.getWindow().setType(
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                newDialog.getWindow().addFlags(
                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                newDialog.show();
            }
        }
    }
};

manager.addPrimaryClipChangedListener(listener);

This function worked fine under Android 9 whenever I copy a URL in other APPs. However, under Android 11 environment the same strategy only responds to copying URL inside the APP. After searching on Bing I didn't seem to find any API changes concerning clipboard, but I do know Android 11 enhances security and privacy, e.g., by not allowing getting IMEI number of my cellphone. Does that account for failure of my APP on Android 11 to detect clipboard changes outside the APP. What's the workaround? It's an APP for personal use only and under my control. I feel more and more frustrated about losing these tiny conveniences.


Solution

  • Does that account for failure of my APP on Android 11 to detect clipboard changes outside the APP

    The change came in Android 10: "Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher."

    What's the workaround?

    Implement your own IME, perhaps.