实现方案
- 安卓监听特定广播,启动服务来读写安卓剪贴板
- 电脑端通过adb命令发送广播调用安卓客户端对应服务
class ClipperReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val cb = context
.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
if (isActionSet(intent.action)) {
val text = intent.getStringExtra(EXTRA_TEXT)
if (text != null) {
cb.setPrimaryClip(ClipData.newPlainText("", text))
resultCode = Activity.RESULT_OK
resultData = "Copied to phone."
} else {
resultCode = Activity.RESULT_CANCELED
resultData = "No text is provided. Use -e text \"text to be pasted\""
}
} else if (isActionGet(intent.action)) {
val clip: CharSequence = cb.primaryClip.toString()
resultCode = Activity.RESULT_OK
resultData = clip.toString()
}
}
private fun isActionGet(action: String?): Boolean {
return ACTION_GET == action || ACTION_GET_SHORT == action
}
private fun isActionSet(action: String?): Boolean {
return ACTION_SET == action || ACTION_SET_SHORT == action
}
}
使用方法
1. 安装共享剪贴板app
https://gitee.com/cxyzy1/adbShareClipboard/blob/master/apks/app-debug.apk
2. 在手机上启动app 3. 将手机通过usb线连接到Mac 4. 修改手机剪贴板内容:电脑端执行:
adb shell am broadcast -a clipper.set -e text "电脑上的内容"
然后手机上就可以直接粘贴了.
5. 获取手机剪贴板内容:电脑端执行:
adb shell am broadcast -a clipper.get|grep data|cut -d"=" -f3|sed 's/\"//g'|pbcopy
然后直接粘贴就可以了
完整源代码https://gitee.com/cxyzy1/adbShareClipboard