Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

android - ClipboardManager OnPrimaryClipChangedListener is called twice for every copy

When I copy text to the clipboard onPrimaryClipChanged method is called twice. Any ideas why?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    final ClipboardManager cliboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

    cliboardManager
            .addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {

                @Override
                public void onPrimaryClipChanged() {
                    ClipData clipData = cliboardManager.getPrimaryClip();
                    System.out
                            .println("********** clip changed, clipData: "
                                    + clipData.getItemAt(0));
                }
            });
    return true;
}

Test case: Copying the text "continue" from the BBC web site will result in the following output:

continue

continue

But if I debug the program I can see that the clipData object has value:

ClipData { text/plain {T:continue } }

the first time onPrimaryClipChanged() is called and

ClipData { text/plain "BBC - Homepage" {T:continue } }

the next time onPrimaryClipChanged() is called.

So basically the first time ClipDescription is { text/plain } and the second time is ClipDescription { text/plain "BBC - Homepage" } (i.e including the title of the web page)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I assume you didn't register multiple listeners, I can't say it is bug, you still you can workaround it. Try something like this:

   String mPreviousText = "";

   cliboardManager
                .addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {

                    @Override
                    public void onPrimaryClipChanged() {
                        ClipData clipData = cliboardManager.getPrimaryClip();
                        System.out
                                .println("********** clip changed, clipData: "
                                        + clipData.getItemAt(0));
                         ClipData.Item item = clipData.getItemAt(0);
                         if(mPreviousText.equals(item.getText().toString())) return;
                         else{
                            /// do something
                            mPrevousText = item.getText().toString();
                         }
                    }
                });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...