如何在Android Q(10)中以编程方式访问剪贴板数据? [英] How to access clipboard data programmatically in Android Q (10)?

查看:143
本文介绍了如何在Android Q(10)中以编程方式访问剪贴板数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道在后台通过Clipboard Manager在后台停止读取数据的操作已由Google在Android Q中停止,因此无论如何,当用户返回活动时无需用户粘贴并且没有粘贴按钮,我仍然需要将直接复制的数据粘贴到编辑文本中.

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.

问题在于,尝试使用 getPrimaryClip()读取数据会返回 null .

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>

推荐答案

您应该在

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.

这篇关于如何在Android Q(10)中以编程方式访问剪贴板数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆