Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access clipboard data programmatically in Android Q (10)?

As we know read data by Clipboard Manager in the background was stopped by Google in android Q, so I need anyway to paste data copied directly in edit text when a user returns to activity without user make a paste and without paste button.

The issue is that trying to read the data with getPrimaryClip() returns null.

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_copy_and_paste);

           ed_editText = findViewById(R.id.ed_editText);

    }
    @Override
    protected void onResume() {
        super.onResume();
           getCopy()
        }

    private void getCopy() {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                if (clipboard != null && clipboard.hasPrimaryClip() && clipboard.getPrimaryClip() != null) {
                    CharSequence clip = clipboard.getPrimaryClip().getItemAt(0).coerceToText(CopyAndPasteActivity.this).toString();
                        ed_editText.setText(clip.toString());
                }      

    }

XML

      <EditText
                        android:id="@+id/ed_editText"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="24dp"
                        android:layout_marginStart="24dp"
                        android:maxLines="1"
                        android:lines="1"
                        android:focusable="true"
                        android:textSize="14sp"
                        android:inputType="text"
                        android:focusableInTouchMode="true"
                        android:layout_weight="1"
                        android:background="@null" >
                    <requestFocus />
                    </EditText>

like image 968
user3661581 Avatar asked Jan 24 '20 20:01

user3661581


1 Answers

You should access the clipboard in Window.Callback.onWindowFocusChanged(true), as that is the moment at which you gain input focus, which is required to read the clipboard in Android 10 (Q). You don't yet necessarily have input focus in onResume.

like image 83
Ryan M Avatar answered Oct 18 '22 23:10

Ryan M