在Android中多次调用onPrimaryClipchanged()

时间:2015-02-12 19:41:56

标签: android

我已经实现了后台服务来监听系统范围内的剪贴板事件..

服务实施:

public class ClipService extends Service {
ClipboardManager cm;

@Override
public void onCreate() {
    Log.d("FRAG","onCreate called...");
    super.onCreate();
    cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cm.addPrimaryClipChangedListener(new ClipboardListener());
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    cm.removePrimaryClipChangedListener(new ClipboardListener());
}

class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener{

     @Override
     public void onPrimaryClipChanged() {
        Log.d("FRAG","onPrimaryClipChanged called..");
        if(cm!=null) {
            String s1 = cm.getPrimaryClip().getItemAt(0).coerceToText(ClipService.this).toString();
            ContentValues cv = new ContentValues();
            cv.put(DatabaseHelper.CONTENT,s1);
            getContentResolver().insert(DataProvider.CONTENT_URI, cv);//Insert using Content provider
        }
     }
}
}

现在我担心的是,对于复制到剪贴板的每个文本,都会为单个复制事件插入三个条目...即。 onPrimaryClipChanged被调用三次..

我正在使用`Log.d(“FRAG”,“onPrimaryClipChanged called ..”);并且它被记录了3次,所以问题似乎是每个剪贴板更改事件被调用3次函数而不插入部分代码。

它可能被调用3次的原因是什么?

1 个答案:

答案 0 :(得分:1)

这是WebView / Chrome的已知问题。我通过忽略某个阈值(例如50毫秒)内的重复事件来解决此问题

ClipboardManager.OnPrimaryClipChangedListener primaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
    private static final long THRESHOLD_MS = 50;
    private long lastChangedTime = 0;
    private String lastString = "";
    @Override
    public void onPrimaryClipChanged() {
        try {
            String str = clipMan.getText().toString();

            // Copying text from certain places will trigger multiple events (e.g. Chrome/WebView generates 3 events)
            // Ignore the duplicated events
            if (System.currentTimeMillis() - lastChangedTime < THRESHOLD_MS && Objects.equals(lastString, str)) {
                return;
            }

            lastChangedTime = System.currentTimeMillis();
            lastString = str;

            // Rest of the logic
            ...
        }
    }
}