Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

基於 WiFi 的無線 HID 設備實現——用手機當電腦觸摸板

編輯:關於 Android 程式設計

某天突然冒出一個念頭:能不能用手指在手機屏上滑動,去控制電腦的鼠標?也就是把手上的 Android 設備變成 PC 的觸摸板。

要落地這個想法,第一個要回答的問題是:手機和電腦之間靠什麼通信?這項技術必須兩端都支持。可選的基本只有 WiFi 和藍牙。

藍牙提供的是個人局域網級別的安全無線通信,功耗相對更低,特別是 BLE 出現之後,功耗已經能與 Zigbee 掰手腕,而且 Android 也支持基於藍牙的 socket 操作。問題出在 PC 端——Java 世界對藍牙 socket 的支持相當糟糕,實現起來瑣碎又易踩坑。反觀 WiFi,功耗雖然遲一些,但實現難度低到只需要一個 socket 就能跑通。權衡之下,第一版決定採用 WiFi 作為傳輸層。

傳輸方案定了,接下來是更關鍵的一層:傳什麼數據、怎麼組織、用什麼協議。這部分設計直接決定後續的可擴展性,一旦這裡偷懶,後期維護會變成災難。反覆權衡之後,選擇用 Google 的 Protobuf 封裝全部消息——它靈活、輕量、高效,正好是這個場景需要的特質。

業餘時間折騰幾天後,一個可運行的初級版本誕生了,基本需求都能滿足。代碼已開源在 GitHub:https://github.com/CreateChance/WirelessHid

UI 的設計

目標是用手機模擬一個 touchpad 加一個 keyboard,那麼界面就必須貼近我們熟悉的實體形態。設計下來,touchpad 部分做成一個 Fragment,布局如下:

 <linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"> <linearlayout android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:orientation="horizontal"> <linearlayout android:id="@+id/speed_control" android:layout_height="match_parent" android:layout_width="65dip" android:orientation="vertical"> <togglebutton android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:tag="1" android:textOff="@string/speed_slow" android:textOn="@string/speed_slow" /> <togglebutton android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:tag="3" android:textOff="@string/speed_medium" android:textOn="@string/speed_medium" /> <togglebutton android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:tag="5" android:textOff="@string/speed_fast" android:textOn="@string/speed_fast" /> </linearlayout> <view android:id="@+id/touchpad" android:layout_height="match_parent" android:layout_weight="1" android:layout_width="0dp" /> <view android:background="#2b2b2b" android:id="@+id/scrollzone" android:layout_height="match_parent" android:layout_width="65dip" /> <linearlayout android:id="@+id/scroll_speed_control" android:layout_height="match_parent" android:layout_width="65dip" android:orientation="vertical"> <togglebutton android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:tag="1" android:textOff="@string/speed_slow" android:textOn="@string/speed_slow" /> <togglebutton android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:tag="3" android:textOff="@string/speed_medium" android:textOn="@string/speed_medium" /> <togglebutton android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent" android:tag="5" android:textOff="@string/speed_fast" android:textOn="@string/speed_fast" /> </linearlayout> </linearlayout> <linearlayout android:id="@+id/buttons" android:layout_height="65dip" android:layout_width="match_parent" android:orientation="horizontal"> <button android:id="@+id/left_button" android:layout_height="match_parent" android:layout_weight="1" android:layout_width="0dp" android:tag="0" android:text="left" /> <button android:layout_height="match_parent" android:layout_weight="1" android:layout_width="0dp" android:tag="1" /> <button android:id="@+id/right_button" android:layout_height="match_parent" android:layout_weight="1" android:layout_width="0dp" android:tag="2" android:text="right" /> </linearlayout></linearlayout>

運行效果:

鍵盤部分的布局:

 <linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"> <linearlayout android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="horizontal"> <textview android:background="@color/led_off" android:id="@+id/led_numlock" android:text="@string/led_numlock" /> <textview android:background="@color/led_off" android:id="@+id/led_capslock" android:text="@string/led_capslock" /> <textview android:background="@color/led_off" android:id="@+id/led_scrolllock" android:text="@string/led_scrolllock" /> </linearlayout> <linearlayout android:id="@+id/keyboard" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> </linearlayout> </linearlayout>

這裡先用三個 TextView 模擬真實鍵盤上的三盞指示燈:Num Lock、Caps Lock、Scroll Lock。下方是一個空的 LinearLayout 容器,用來裝真正的鍵盤布局。

之所以要留這個容器,是因為手機屏幕實在放不下標準鍵盤的全部按鍵,只能分區展示。目前劃成兩部分:主鍵盤區(26 個字母、上排數字、12 個功能鍵等最常用的鍵)與「導航鍵 + 數字小鍵盤」區,後兩者合併在一起。

主鍵盤部分:

 <keyboard> <layout> <key keycode="27" keylabel="Esc" /> <key keycode="112" keylabel="F1" /> <key keycode="113" keylabel="F2" /> <key keycode="114" keylabel="F3" /> <key keycode="115" keylabel="F4" /> <key keycode="116" keylabel="F5" /> <key keycode="117" keylabel="F6" /> <key keycode="118" keylabel="F7" /> <key keycode="119" keylabel="F8" /> <key keycode="120" keylabel="F9" /> <key keycode="121" keylabel="F10" /> <key keycode="122" keylabel="F11" /> <key keycode="123" keylabel="F12" /> <key keycode="127" keylabel="Del" /> </layout> <layout> <key keycode="192" keylabel="'" shiftlabel="~" /> <key keycode="49" keylabel="1" shiftlabel="!" /> <key keycode="50" keylabel="2" shiftlabel="@" /> <key keycode="51" keylabel="3" shiftlabel="#" /> <key keycode="52" keylabel="4" shiftlabel="$" /> <key keycode="53" keylabel="5" shiftlabel="%" /> <key keycode="54" keylabel="6" shiftlabel="^" /> <key keycode="55" keylabel="7" shiftlabel="&amp;" /> <key keycode="56" keylabel="8" shiftlabel="*" /> <key keycode="57" keylabel="9" shiftlabel="(" /> <key keycode="48" keylabel="0" shiftlabel=")" /> <key keycode="45" keylabel="-" shiftlabel="_" /> <key keycode="61" keylabel="=" shiftlabel="+" /> <key keycode="8" keylabel="Backspace ←" weight="1.5" /> </layout> <layout> <key keycode="9" keylabel="Tab ↳" weight="1.5" /> <key keycode="81" keylabel="Q" /> <key keycode="87" keylabel="W" /> <key keycode="69" keylabel="E" /> <key keycode="82" keylabel="R" /> <key keycode="84" keylabel="T" /> <key keycode="89" keylabel="Y" /> <key keycode="85" keylabel="U" /> <key keycode="73" keylabel="I" /> <key keycode="79" keylabel="O" /> <key keycode="80" keylabel="P" /> <key keycode="91" keylabel="[" shiftlabel="{" /> <key keycode="93" keylabel="]" shiftlabel="}" /> <key keycode="92" keylabel="\" shiftlabel="|" /> </layout> <layout> <key keycode="20" keylabel="Caps Lock" weight="1.5" /> <key keycode="65" keylabel="A" /> <key keycode="83" keylabel="S" /> <key keycode="68" keylabel="D" /> <key keycode="70" keylabel="F" /> <key keycode="71" keylabel="G" /> <key keycode="72" keylabel="H" /> <key keycode="74" keylabel="J" /> <key keycode="75" keylabel="K" /> <key keycode="76" keylabel="L" /> <key keycode="59" keylabel=";" shiftlabel=":" /> <key keycode="44" keylabel="'" shiftlabel="&quot;" /> <key keycode="10" keylabel="Enter ↵" weight="3.0" /> </layout> <layout> <key keycode="16" keyfunc="Shift" keylabel="Shift ⇧" weight="1.5" /> <key keycode="90" keylabel="Z" /> <key keycode="88" keylabel="X" /> <key keycode="67" keylabel="C" /> <key keycode="86" keylabel="V" /> <key keycode="66" keylabel="B" /> <key keycode="78" keylabel="N" /> <key keycode="77" keylabel="M" /> <key keycode="44" keylabel="," shiftlabel="&lt;" /> <key keycode="46" keylabel="." shiftlabel="&gt;" /> <key keycode="47" keylabel="/" shiftlabel="?" /> <key keycode="16" keyfunc="Shift" keylabel="Shift ⇧" weight="1.5" /> </layout> <layout> <key keycode="17" keylabel="Ctrl" weight="1.5" /> <key keycode="524" keylabel="Win" /> <key keycode="18" keylabel="Alt" /> <key keycode="32" keylabel=" " weight="10.0" /> <key keycode="18" keylabel="Alt" /> <key keycode="524" keylabel="Win" /> <key keycode="93" keylabel="Menu" /> <key keycode="17" keylabel="Ctrl" weight="1.5" /> </layout> </keyboard>

導航鍵部分:

 <keyboard> <layout> <key keycode="154" keylabel="Print\nScreen" /> <key keycode="145" keylabel="Scroll\nLock" /> <key keycode="19" keylabel="Pause\nBreak" /> </layout> <layout> <key keycode="155" keylabel="Insert" /> <key keycode="36" keylabel="Home" /> <key keycode="33" keylabel="Page Up" /> </layout> <layout> <key keycode="127" keylabel="Delete" /> <key keycode="35" keylabel="End" /> <key keycode="34" keylabel="Page Down" /> </layout> <layout> <key visible="false" /> <key keycode="38" keylabel="↑" /> <key visible="false" /> </layout> <layout> <key keycode="37" keylabel="←" /> <key keycode="40" keylabel="↓" /> <key keycode="39" keylabel="→" /> </layout> </keyboard>

數字鍵部分:

 <keyboard> <layout> <key keycode="144" keylabel="Num\nLock" /> <key keycode="111" keylabel="/" /> <key keycode="106" keylabel="*" /> <key keycode="45" keylabel="-" /> </layout> <layout> <key keycode="0103" keylabel="7\nHome" /> <key keycode="104" keylabel="8 ↑" /> <key keycode="105" keylabel="9\nPgUp" /> <key keycode="521" keylabel="+" /> </layout> <layout> <key keycode="100" keylabel="4\n←" /> <key keycode="101" keylabel="5" /> <key keycode="102" keylabel="6\n→" /> <key visible="false" /> </layout> <layout> <key keycode="97" keylabel="1\nEnd" /> <key keycode="98" keylabel="2 ↓" /> <key keycode="99" keylabel="3\nPgDn" /> <key visible="false" /> </layout> <layout> <key keycode="96" keylabel="0\nIns" weight="2.0" /> <key keycode="110" keylabel=".\nDel" /> <key keycode="10" keylabel="Enter" /> </layout> </keyboard>

這套布局用自定義的 <layout> 與 <key> 標簽描述,運行時由 XmlResourceParser 解析,再動態組裝成真正的 View 層級。兩部分鍵盤的實機效果:

主鍵盤:

從鍵盤(導航鍵與數字鍵):

代碼設計

Server 端

Server 整體就是一個 Android App,結構並不複雜。這裡只說明各部分的職責與關鍵代碼片段,完整實現可參考 GitHub 倉庫(https://github.com/CreateChance/WirelessHid)。

代碼大致分布:

MainActivity

主界面,本質上是 MouseFragment 的容器,另外負責攔截返回鍵:1.5 秒內連點兩次才退出應用,避免誤觸。邏輯很輕。

WirelessHidService

整個 App 的核心服務,真正把數據發出去的地方。它通過 Looper 與 Handler 把消息隊列裡的數據逐條發送。發送部分的邏輯如下:

 private class DataSendThread extends Thread { private OutputStream os = null; @Override public void run() { super.run(); Looper.prepare(); try { Log.d(TAG, "I'm waiting for connecting."); mServerSocket = new ServerSocket(Constant.HID_TCP_PORT); mServerSocket.setReuseAddress(true); mSocket = mServerSocket.accept(); os = mSocket.getOutputStream(); Toast.makeText(getApplicationContext(), "Client connected!", Toast.LENGTH_SHORT).show(); Log.d(TAG, "client connected!"); } catch (IOException e) { e.printStackTrace(); return; } mDataSendHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); try { ((WirelessHidProto.HidData)msg.obj).writeDelimitedTo(os); } catch (IOException e) { Log.d(TAG, "IOException, close all resource."); mDataSendHandler = null; if (mListener != null) { mListener.onHandlerChanged(mDataSendHandler); } this.getLooper().quit(); sendBroadcast(new Intent(ACTION_RESET_CONNECTION)); } finally { try { mServerSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }; if (mListener != null) { mListener.onHandlerChanged(mDataSendHandler); } Looper.loop(); } }

界面 Fragment 通過 Handler 與 Service 交互。Fragment 需要實現 Service 的 DataHandlerListener 接口,一旦 Handler 發生變化就收到通知,從而能拿到最新的對象引用:

 public interface DataHandlerListener { void onHandlerChanged(Handler handler); }
 public void setListener(DataHandlerListener listener) { this.mListener = listener; }

也可以主動獲取:

 public Handler getDataSendHandler() { return this.mDataSendHandler; }

發送環節直接用 Protobuf 的序列化接口,詳細用法參考官方 Java 教程:https://developers.google.com/protocol-buffers/docs/javatutorial

MouseFragment

嵌套在 MainActivity 中的 Fragment,主要職責有四項。

一、捕獲觸摸屏的移動與點擊:

 @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //single and double click handle here. mPrevX = (int) event.getX(); mPrevY = (int) event.getY(); time = new Date().getTime(); break; case MotionEvent.ACTION_UP: if (new Date().getTime() - time < mDoubleClickTimeThreshold) { if ((int) event.getX() - mPrevX < mDoubleClickPosThreshold && (int) event.getY() - mPrevY < mDoubleClickPosThreshold) { mouseClickPress(Constant.MOUSE_BUTTON_LEFT); mouseClickRelease(Constant.MOUSE_BUTTON_LEFT); } } case MotionEvent.ACTION_MOVE: //mouse move handle here. int x = (int) (event.getX() * mSpeed); int y = (int) (event.getY() * mSpeed); mouseMove(x - mPrevX, y - mPrevY); mPrevX = x; mPrevY = y; break; } return true; }

二、鼠標左右鍵(用 Button 模擬):

 // setup buttons ViewGroup bar = (ViewGroup) view.findViewById(R.id.buttons); int count = bar.getChildCount(); for (int i = 0; i < count; i++) { View child = bar.getChildAt(i); try { Button button = (Button) child; button.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int which = Integer.valueOf((String) v.getTag()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //0 is left button / 1 reserved / 2 is right button if (which == 0) { mouseClickPress(Constant.MOUSE_BUTTON_LEFT); } else if (which == 1) { //Do nothing for now. } else if (which == 2) { mouseClickPress(Constant.MOUSE_BUTTON_RIGHT); } break; case MotionEvent.ACTION_UP: if (which == 0) { mouseClickRelease(Constant.MOUSE_BUTTON_LEFT); } else if (which == 1) { //Do nothing for now. } else if (which == 2) { mouseClickRelease(Constant.MOUSE_BUTTON_RIGHT); } break; } return false; } }); } catch (ClassCastException e) { // not a button :) } }

三、滾軸滾動:

 // setup scroll mScrollZone = view.findViewById(R.id.scrollzone); mScrollZone.setOnTouchListener(new OnTouchListener() { private int mPrevY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mPrevY = (int) (event.getY() * mScrollSpeed); break; case MotionEvent.ACTION_MOVE: int amt = (int) (event.getY() * mScrollSpeed); mouseScroll(mPrevY - amt); mPrevY = amt; break; } return true; } });

四、鼠標移動速度與滾動速度的調節。

 // setup speed controls bar = (ViewGroup) view.findViewById(R.id.speed_control); count = bar.getChildCount(); for (int i = 0; i < count; i++) { View child = bar.getChildAt(i); try { ToggleButton button = (ToggleButton) child; button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ToggleButton button = (ToggleButton) v; // do not allow to uncheck button if (!button.isChecked()) { button.setChecked(true); return; } updateSpeed(Integer.parseInt((String) button.getTag())); } }); } catch (ClassCastException e) { // not a button :) } }
 // setup scroll speed controls bar = (ViewGroup) view.findViewById(R.id.scroll_speed_control); count = bar.getChildCount(); for (int i = 0; i < count; i++) { View child = bar.getChildAt(i); try { ToggleButton button = (ToggleButton) child; button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ToggleButton button = (ToggleButton) v; if (!button.isChecked()) { button.setChecked(true); return; } updateScrollSpeed(Integer.parseInt((String) button.getTag())); } }); } catch (ClassCastException e) { // not a button :) } }

更新移動速度與滾動速度的思路一致,都是遍歷容器子項、按 tag 值同步勾選狀態:

 private void updateSpeed(int newSpeed) { mSpeed = newSpeed; ViewGroup bar = (ViewGroup) getView().findViewById(R.id.speed_control); int count = bar.getChildCount(); for (int i = 0; i < count; i++) { View child = bar.getChildAt(i); try { ToggleButton button = (ToggleButton) child; int speed = Integer.parseInt((String) button.getTag()); button.setChecked(speed == newSpeed); } catch (ClassCastException e) { // not a button :) } } }
 private void updateScrollSpeed(int newSpeed) { mScrollSpeed = newSpeed; ViewGroup bar = (ViewGroup) getView().findViewById(R.id.scroll_speed_control); int count = bar.getChildCount(); for (int i = 0; i < count; i++) { View child = bar.getChildAt(i); try { ToggleButton button = (ToggleButton) child; int speed = Integer.parseInt((String) button.getTag()); button.setChecked(speed == newSpeed); } catch (ClassCastException e) { // not a button :) } } }

KeyboardFragment

鍵盤 Fragment,本質上是一個 FragmentActivity。具體的鍵盤通過 addView 掛到容器上:

 keyboard = (ViewGroup) this.findViewById(R.id.keyboard); keyboard.addView(view);

針對兩類鍵盤分別提供了創建入口。主鍵盤:

 private View creatQwertyKeyboard(Context context) { return createKeyboard(context, R.xml.qwerty_keyboard); }

從鍵盤(把導航區與數字區組裝到一個容器裡):

 private View createNavigationAndNumericKeyboard(Context context) { ViewGroup view = (ViewGroup) View.inflate(context, R.layout.numeric_keyboard, null); ViewGroup child; child = (ViewGroup) view.findViewById(R.id.navigation_keyboard); child.addView(createKeyboard(context, R.xml.navigation_keyboard)); child = (ViewGroup) view.findViewById(R.id.numeric_keyboard); child.addView(createKeyboard(context, R.xml.numeric_keyboard)); return view; }

兩者最終都落到統一的 createKeyboard,其中封裝了按鍵按下與抬起的處理,包括長按判定與三盞指示燈的狀態切換:

 private Keyboard createKeyboard(Context context, int xmlResourceID) { final Keyboard keyboard = new Keyboard(context, xmlResourceID); keyboard.setKeyboardListener(new Keyboard.KeyboardListener() { @Override public void onKeyUp(int keyCode) { Log.d(TAG, "up keycode: " + keyCode); if (mDataSendHandler != null) { mDataSendHandler.removeCallbacks(mLongPressCheckTask); } if (mIsLongPressed) { mIsLongPressed = false; WirelessHidProto.HidData data = WirelessHidProto.HidData.newBuilder() .setType(WirelessHidProto.HidData.DataType.KEYBOARD_LONG_RELEASE) .setKeyboardValue(keyCode).build(); if (mDataSendHandler != null) { mDataSendHandler.obtainMessage(0, data).sendToTarget(); } } else { WirelessHidProto.HidData data = WirelessHidProto.HidData.newBuilder() .setType(WirelessHidProto.HidData.DataType.KEYBOARD_HIT) .setKeyboardValue(keyCode).build(); if (mDataSendHandler != null) { mDataSendHandler.obtainMessage(0, data).sendToTarget(); } } } @Override public void onKeyDown(int keyCode) { Log.d(TAG, "key down: " + keyCode); if (keyCode == 144) { mIsNumLockActive = !mIsNumLockActive; KeyboardFragment.this.findViewById(R.id.led_numlock). setBackgroundColor(getResources().getColor(mIsNumLockActive ? R.color.led_on : R.color.led_off)); } else if (keyCode == 20) { mIsCapsLockActive = !mIsCapsLockActive; KeyboardFragment.this.findViewById(R.id.led_capslock). setBackgroundColor(getResources().getColor(mIsCapsLockActive ? R.color.led_on : R.color.led_off)); } else if (keyCode == 145) { mIsScrollLockActive = !mIsScrollLockActive; KeyboardFragment.this.findViewById(R.id.led_scrolllock). setBackgroundColor(getResources().getColor(mIsScrollLockActive ? R.color.led_on : R.color.led_off)); } else if (mDataSendHandler != null) { mLongPressCheckTask.setKeyCode(keyCode); mDataSendHandler.postDelayed(mLongPressCheckTask, 1000); } } }); return keyboard; }

返回的 Keyboard 是 LinearLayout 的子類,它用 XmlResourceParser 解析前面定義的 XML,把 <layout> 遞歸展開成 LinearLayout,把 <key> 變成自定義的 Key 控件:

 private LinearLayout parseKeyLayout(Context context, XmlResourceParser xmlParser) throws XmlPullParserException, IOException { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(new LayoutParams( xmlParser.getAttributeIntValue(null, "width", LayoutParams.MATCH_PARENT), xmlParser.getAttributeIntValue(null, "height", 0), xmlParser.getAttributeFloatValue(null, "weight", 1.0f))); linearLayout.setOrientation(xmlParser.getAttributeIntValue(null, "orientation", LinearLayout.HORIZONTAL)); String tag; do { xmlParser.next(); tag = xmlParser.getName(); if (xmlParser.getEventType() == XmlResourceParser.START_TAG) { if (tag.equals(XML_TAG_LAYOUT)) { linearLayout.addView(parseKeyLayout(context, xmlParser)); } else if (tag.equals(XML_TAG_KEY)) { Key.KeyAttributes attrs = new Key.KeyAttributes(); attrs.keyFunction = getStringAttributeValue(xmlParser, "keyFunc", ""); attrs.mainLabel = getStringAttributeValue(xmlParser, "keyLabel", ""); attrs.shiftLabel = getStringAttributeValue(xmlParser, "shiftLabel", ""); attrs.keyCode = xmlParser.getAttributeIntValue(null, "keyCode", 0); Key key = new Key(context, attrs); key.setLayoutParams(new LayoutParams( xmlParser.getAttributeIntValue(null, "width", 0), xmlParser.getAttributeIntValue(null, "height", LayoutParams.MATCH_PARENT), xmlParser.getAttributeFloatValue(null, "weight", 1))); key.setVisibility(xmlParser.getAttributeBooleanValue(null, "visible", true) ? VISIBLE : INVISIBLE); key.setKeyListener(this); if (attrs.shiftLabel != null & attrs.shiftLabel.length() > 0) { mKeysWithShiftLabel.add(key); } linearLayout.addView(key); } } } while (xmlParser.getEventType() != XmlResourceParser.END_TAG || !tag.equals(XML_TAG_LAYOUT)); return linearLayout; }

WirelessHid.proto

Protobuf 的數據定義文件:

 syntax = "proto2"; option java_package = "com.baniel.wirelesshid"; option java_outer_classname = "WirelessHidProto"; message HidData { enum DataType { MOUSE_MOVE = 0; MOUSE_CLICK_PRESS = 1; MOUSE_CLICK_RELEASE = 2; MOUSE_SCROLL = 3; KEYBOARD_LONG_PRESS = 4; KEYBOARD_LONG_RELEASE = 5; KEYBOARD_HIT = 6; } required DataType type = 1; optional int32 x_shift = 2; optional int32 y_shift = 3; optional int32 mouse_key_value = 4; optional int32 mouse_scroll = 5; optional int32 keyboard_value = 6; }

這裡只定義了一個消息類型 HidData,即 Android 需要發給 PC 的全部數據。字段含消息類型(鼠標移動、按下、釋放、滾軸、鍵盤長按、長按釋放、單擊)、x/y 軸偏移量(PC 系統的鼠標移動以坐標增量為參數)、鼠標按鍵值、滾動值與鍵盤按鍵值。語法細節可查:https://developers.google.com/protocol-buffers/docs/proto

WirelessHidProto 類即由該文件經 Protobuf 編譯器生成。

Client 端

PC 端代碼要簡單得多,只有兩個類:

WirelessHidClient

主類,從 socket 讀取 Android 送來的數據,再通過 Java 的 Robot 類去移動鼠標、模擬鍵盤:

 public static void main(String[] args) { final int HID_TCP_PORT = 34567; Socket mSocket = null; InputStream is = null; HidData data = null; try { mSocket = new Socket(args[0], HID_TCP_PORT); is = mSocket.getInputStream(); mRobot = new Robot(); printClientInfo(mSocket); while (true) { data = HidData.parseDelimitedFrom(is); if (data != null) { handleData(data); } else { break; } } } catch (UnknownHostException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } catch (AWTException e) { System.exit(-1); } System.out.println("Connection lost."); }

具體動作封裝成幾個靜態方法:

 //move mouse pointer to posX,posY of current position. private static void doMouseMove(int posX, int posY) { mRobot.mouseMove(mPrevX + posX, mPrevY + posY); mPrevX += posX; mPrevY += posY; } private static void doMousePress(int keyValue) { mRobot.mousePress(keyValue); } private static void doMouseRelease(int keyValue) { mRobot.mouseRelease(keyValue); } private static void doMouseScroll(int amt) { mRobot.mouseWheel(amt); } private static void doKeyHit(int keyCode) { mRobot.keyPress(keyCode); mRobot.keyRelease(keyCode); } private static void doKeyLongPress(int keyCode) { mRobot.keyPress(keyCode); } private static void doKeyLongRelease(int keyCode) { mRobot.keyRelease(keyCode); }

WirelessHidProto

由 Protobuf 編譯器生成,包含消息對象的序列化與反序列化邏輯。

至此整個實現就梳理完了。感興趣的朋友可以從 GitHub 直接下載編譯好的二進制包試跑(https://github.com/CreateChance/WirelessHid/tree/master/bin)。

運行方式:

Server 端(Android)——安裝 App 後直接啟動即可,前提是手機已接入局域 WiFi,且能與 PC 互通。

Client 端(Linux 或 Windows)——命令行執行:

java -jar WirelessHidClient.jar 你的android設備地址

一點體驗上的提醒:客戶端跑在 Linux 上較為流暢,Windows 下會有明顯卡頓,影響手感。具體原因尚在排查,若有人知道答案,歡迎賜教。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved