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

为君一笑 提交于 2020-07-19 04:01:05

问题


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>


回答1:


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.



来源:https://stackoverflow.com/questions/59903001/how-to-access-clipboard-data-programmatically-in-android-q-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!