Предыстория такова — у меня начались проблемы со звуковой карточкой на компьютере и чтобы лишний раз ее не тревожить я начал использовать в качестве медиаплеера свой старый смартфон на Android’е. Смартфон этот постоянно подключен по USB к моему компьютеру, поэтому я просто воткнул в него свои колонки и запустил программу Вконтакте (там много хорошей музыки можно послушать:) ). Все-бы ничего, но вот неудобно каждый раз попадать в сенсорный экран по кнопкам Пауза/далее — телефон стоит у меня не самым удобным образом по отношению ко мне. Решено было переключать музыку с компьютера.
В интернете мною не было найдено простого как «раз-два» решения такой, казалось бы типичной проблемы, как возможность просто управлять медиаплеером вконтакте на андроид с компьютера, да и вообще любым плеером. Есть большие, специализированные программы и сайты, не говоря уже о VNC, которые позволяют это делать, а минималистичного приложения для Linux — нет, или я плохо искал. Вот управление плеером в ubuntu с андроид — таких статей навалом. Эта статья о том, как я в очередной раз изобрел велосипед и решил, как минимум для себя такую проблему.
Вообще сказать — первая моя идея была насчет возможности управления смартфоном посредством ADB и я начал копать именно в его сторону. До этого вся моя работа с ADB заключалась в отладке Java приложений с помощью DDMS. Но ища материал по теме управления смартфоном с android с Ubuntu я узнал, что с помощью команд ADB возможна эмуляция нажатия клавиш на мобильном устройстве.
Испробовав в терминале все возможные комбинации команд по управлению воспроизведением на смартфоне я отобрал для себя пять необходимых: Предыдущий трек, следующий, пауза/плэй, громкость вверх и вниз. Естественно, набирать каждый раз вручную в терминале все команды будет не удобно (проще переключить на смартфоне) и я воспользовался полюбившимся мне за простоту создания легких утилит с интерфейсом Lazarus чтобы оформить для всего этого GUI, которое возможно будет вызывать по «горячей клавише».
Для начала нам понадобиться сам ADB. Его можно найти в комплекте android-sdk — для разработчиков под Android. Он находится по пути android-sdk/platform-tools/adb. SDK можно загрузить на http://developer.android.com/sdk/index.html .
Пользователям Ubuntu повезло больше — adb имеется в репозиториях:
sudo apt-get install android-tools-adb
После установки подключи свой смартфон по USB и проверь его нахождение командой:
adb devices
Не забудь включить «Отладку по USB» в настройках android.
Если все ок — то можно начинать пользоваться моей утилитой или написанной тобой по такому-же принципу.
Принцип реализации такой: с помощью ADB мы имеем возможность эмулировать нажатия кнопок на смартфоне командой:
adb shell input keyevent КОД/НЭЙМ_кнопки
Вот список доступных для эмуляции клавиш, если тебе захочется сделать нечто похожее, но с другим функционалом:
KEYCODE_0 Key code constant: '0' key. KEYCODE_1 Key code constant: '1' key. KEYCODE_2 Key code constant: '2' key. KEYCODE_3 Key code constant: '3' key. KEYCODE_3D_MODE Key code constant: 3D Mode key. KEYCODE_4 Key code constant: '4' key. KEYCODE_5 Key code constant: '5' key. KEYCODE_6 Key code constant: '6' key. KEYCODE_7 Key code constant: '7' key. KEYCODE_8 Key code constant: '8' key. KEYCODE_9 Key code constant: '9' key. KEYCODE_A Key code constant: 'A' key. KEYCODE_ALT_LEFT Key code constant: Left Alt modifier key. KEYCODE_ALT_RIGHT Key code constant: Right Alt modifier key. KEYCODE_APOSTROPHE Key code constant: ''' (apostrophe) key. KEYCODE_APP_SWITCH Key code constant: App switch key. KEYCODE_ASSIST Key code constant: Assist key. KEYCODE_AT Key code constant: '@' key. KEYCODE_AVR_INPUT Key code constant: A/V Receiver input key. KEYCODE_AVR_POWER Key code constant: A/V Receiver power key. KEYCODE_B Key code constant: 'B' key. KEYCODE_BACK Key code constant: Back key. KEYCODE_BACKSLASH Key code constant: '\' key. KEYCODE_BOOKMARK Key code constant: Bookmark key. KEYCODE_BREAK Key code constant: Break / Pause key. KEYCODE_BRIGHTNESS_DOWN Key code constant: Brightness Down key. KEYCODE_BRIGHTNESS_UP Key code constant: Brightness Up key. KEYCODE_BUTTON_1 Key code constant: Generic Game Pad Button #1. KEYCODE_BUTTON_10 Key code constant: Generic Game Pad Button #10. KEYCODE_BUTTON_11 Key code constant: Generic Game Pad Button #11. KEYCODE_BUTTON_12 Key code constant: Generic Game Pad Button #12. KEYCODE_BUTTON_13 Key code constant: Generic Game Pad Button #13. KEYCODE_BUTTON_14 Key code constant: Generic Game Pad Button #14. KEYCODE_BUTTON_15 Key code constant: Generic Game Pad Button #15. KEYCODE_BUTTON_16 Key code constant: Generic Game Pad Button #16. KEYCODE_BUTTON_2 Key code constant: Generic Game Pad Button #2. KEYCODE_BUTTON_3 Key code constant: Generic Game Pad Button #3. KEYCODE_BUTTON_4 Key code constant: Generic Game Pad Button #4. KEYCODE_BUTTON_5 Key code constant: Generic Game Pad Button #5. KEYCODE_BUTTON_6 Key code constant: Generic Game Pad Button #6. KEYCODE_BUTTON_7 Key code constant: Generic Game Pad Button #7. KEYCODE_BUTTON_8 Key code constant: Generic Game Pad Button #8. KEYCODE_BUTTON_9 Key code constant: Generic Game Pad Button #9. KEYCODE_BUTTON_A Key code constant: A Button key. KEYCODE_BUTTON_B Key code constant: B Button key. KEYCODE_BUTTON_C Key code constant: C Button key. KEYCODE_BUTTON_L1 Key code constant: L1 Button key. KEYCODE_BUTTON_L2 Key code constant: L2 Button key. KEYCODE_BUTTON_MODE Key code constant: Mode Button key. KEYCODE_BUTTON_R1 Key code constant: R1 Button key. KEYCODE_BUTTON_R2 Key code constant: R2 Button key. KEYCODE_BUTTON_SELECT Key code constant: Select Button key. KEYCODE_BUTTON_START Key code constant: Start Button key. KEYCODE_BUTTON_THUMBL Key code constant: Left Thumb Button key. KEYCODE_BUTTON_THUMBR Key code constant: Right Thumb Button key. KEYCODE_BUTTON_X Key code constant: X Button key. KEYCODE_BUTTON_Y Key code constant: Y Button key. KEYCODE_BUTTON_Z Key code constant: Z Button key. KEYCODE_C Key code constant: 'C' key. KEYCODE_CALCULATOR Key code constant: Calculator special function key. KEYCODE_CALENDAR Key code constant: Calendar special function key. KEYCODE_CALL Key code constant: Call key. KEYCODE_CAMERA Key code constant: Camera key. KEYCODE_CAPS_LOCK Key code constant: Caps Lock key. KEYCODE_CAPTIONS Key code constant: Toggle captions key. KEYCODE_CHANNEL_DOWN Key code constant: Channel down key. KEYCODE_CHANNEL_UP Key code constant: Channel up key. KEYCODE_CLEAR Key code constant: Clear key. KEYCODE_COMMA Key code constant: ',' key. KEYCODE_CONTACTS Key code constant: Contacts special function key. KEYCODE_CTRL_LEFT Key code constant: Left Control modifier key. KEYCODE_CTRL_RIGHT Key code constant: Right Control modifier key. KEYCODE_D Key code constant: 'D' key. KEYCODE_DEL Key code constant: Backspace key. KEYCODE_DPAD_CENTER Key code constant: Directional Pad Center key. KEYCODE_DPAD_DOWN Key code constant: Directional Pad Down key. KEYCODE_DPAD_LEFT Key code constant: Directional Pad Left key. KEYCODE_DPAD_RIGHT Key code constant: Directional Pad Right key. KEYCODE_DPAD_UP Key code constant: Directional Pad Up key. KEYCODE_DVR Key code constant: DVR key. KEYCODE_E Key code constant: 'E' key. KEYCODE_EISU Key code constant: Japanese alphanumeric key. KEYCODE_ENDCALL Key code constant: End Call key. KEYCODE_ENTER Key code constant: Enter key. KEYCODE_ENVELOPE Key code constant: Envelope special function key. KEYCODE_EQUALS Key code constant: '=' key. KEYCODE_ESCAPE Key code constant: Escape key. KEYCODE_EXPLORER Key code constant: Explorer special function key. KEYCODE_F Key code constant: 'F' key. KEYCODE_F1 Key code constant: F1 key. KEYCODE_F10 Key code constant: F10 key. KEYCODE_F11 Key code constant: F11 key. KEYCODE_F12 Key code constant: F12 key. KEYCODE_F2 Key code constant: F2 key. KEYCODE_F3 Key code constant: F3 key. KEYCODE_F4 Key code constant: F4 key. KEYCODE_F5 Key code constant: F5 key. KEYCODE_F6 Key code constant: F6 key. KEYCODE_F7 Key code constant: F7 key. KEYCODE_F8 Key code constant: F8 key. KEYCODE_F9 Key code constant: F9 key. KEYCODE_FOCUS Key code constant: Camera Focus key. KEYCODE_FORWARD Key code constant: Forward key. KEYCODE_FORWARD_DEL Key code constant: Forward Delete key. KEYCODE_FUNCTION Key code constant: Function modifier key. KEYCODE_G Key code constant: 'G' key. KEYCODE_GRAVE Key code constant: '`' (backtick) key. KEYCODE_GUIDE Key code constant: Guide key. KEYCODE_H Key code constant: 'H' key. KEYCODE_HEADSETHOOK Key code constant: Headset Hook key. KEYCODE_HENKAN Key code constant: Japanese conversion key. KEYCODE_HOME Key code constant: Home key. KEYCODE_I Key code constant: 'I' key. KEYCODE_INFO Key code constant: Info key. KEYCODE_INSERT Key code constant: Insert key. KEYCODE_J Key code constant: 'J' key. KEYCODE_K Key code constant: 'K' key. KEYCODE_KANA Key code constant: Japanese kana key. KEYCODE_KATAKANA_HIRAGANA Key code constant: Japanese katakana / hiragana key. KEYCODE_L Key code constant: 'L' key. KEYCODE_LANGUAGE_SWITCH Key code constant: Language Switch key. KEYCODE_LEFT_BRACKET Key code constant: '[' key. KEYCODE_M Key code constant: 'M' key. KEYCODE_MANNER_MODE Key code constant: Manner Mode key. KEYCODE_MEDIA_AUDIO_TRACK Key code constant: Audio Track key Switches the audio tracks. KEYCODE_MEDIA_CLOSE Key code constant: Close media key. KEYCODE_MEDIA_EJECT Key code constant: Eject media key. KEYCODE_MEDIA_FAST_FORWARD Key code constant: Fast Forward media key. KEYCODE_MEDIA_NEXT Key code constant: Play Next media key. KEYCODE_MEDIA_PAUSE Key code constant: Pause media key. KEYCODE_MEDIA_PLAY Key code constant: Play media key. KEYCODE_MEDIA_PLAY_PAUSE Key code constant: Play/Pause media key. KEYCODE_MEDIA_PREVIOUS Key code constant: Play Previous media key. KEYCODE_MEDIA_RECORD Key code constant: Record media key. KEYCODE_MEDIA_REWIND Key code constant: Rewind media key. KEYCODE_MEDIA_STOP Key code constant: Stop media key. KEYCODE_MENU Key code constant: Menu key. KEYCODE_META_LEFT Key code constant: Left Meta modifier key. KEYCODE_META_RIGHT Key code constant: Right Meta modifier key. KEYCODE_MINUS Key code constant: '-'. KEYCODE_MOVE_END Key code constant: End Movement key. KEYCODE_MOVE_HOME Key code constant: Home Movement key. KEYCODE_MUHENKAN Key code constant: Japanese non-conversion key. KEYCODE_MUSIC Key code constant: Music special function key. KEYCODE_MUTE Key code constant: Mute key. KEYCODE_N Key code constant: 'N' key. KEYCODE_NOTIFICATION Key code constant: Notification key. KEYCODE_NUM Key code constant: Number modifier key. KEYCODE_NUMPAD_0 Key code constant: Numeric keypad '0' key. KEYCODE_NUMPAD_1 Key code constant: Numeric keypad '1' key. KEYCODE_NUMPAD_2 Key code constant: Numeric keypad '2' key. KEYCODE_NUMPAD_3 Key code constant: Numeric keypad '3' key. KEYCODE_NUMPAD_4 Key code constant: Numeric keypad '4' key. KEYCODE_NUMPAD_5 Key code constant: Numeric keypad '5' key. KEYCODE_NUMPAD_6 Key code constant: Numeric keypad '6' key. KEYCODE_NUMPAD_7 Key code constant: Numeric keypad '7' key. KEYCODE_NUMPAD_8 Key code constant: Numeric keypad '8' key. KEYCODE_NUMPAD_9 Key code constant: Numeric keypad '9' key. KEYCODE_NUMPAD_ADD Key code constant: Numeric keypad '+' key (for addition). KEYCODE_NUMPAD_COMMA Key code constant: Numeric keypad ',' key (for decimals or digit grouping). KEYCODE_NUMPAD_DIVIDE Key code constant: Numeric keypad '/' key (for division). KEYCODE_NUMPAD_DOT Key code constant: Numeric keypad '.' key (for decimals or digit grouping). KEYCODE_NUMPAD_ENTER Key code constant: Numeric keypad Enter key. KEYCODE_NUMPAD_EQUALS Key code constant: Numeric keypad '=' key. KEYCODE_NUMPAD_LEFT_PAREN Key code constant: Numeric keypad '(' key. KEYCODE_NUMPAD_MULTIPLY Key code constant: Numeric keypad '*' key (for multiplication). KEYCODE_NUMPAD_RIGHT_PAREN Key code constant: Numeric keypad ')' key. KEYCODE_NUMPAD_SUBTRACT Key code constant: Numeric keypad '-' key (for subtraction). KEYCODE_NUM_LOCK Key code constant: Num Lock key. KEYCODE_O Key code constant: 'O' key. KEYCODE_P Key code constant: 'P' key. KEYCODE_PAGE_DOWN Key code constant: Page Down key. KEYCODE_PAGE_UP Key code constant: Page Up key. KEYCODE_PERIOD Key code constant: '.' key. KEYCODE_PICTSYMBOLS Key code constant: Picture Symbols modifier key. KEYCODE_PLUS Key code constant: '+' key. KEYCODE_POUND Key code constant: '#' key. KEYCODE_POWER Key code constant: Power key. KEYCODE_PROG_BLUE Key code constant: Blue "programmable" key. KEYCODE_PROG_GREEN Key code constant: Green "programmable" key. KEYCODE_PROG_RED Key code constant: Red "programmable" key. KEYCODE_PROG_YELLOW Key code constant: Yellow "programmable" key. KEYCODE_Q Key code constant: 'Q' key. KEYCODE_R Key code constant: 'R' key. KEYCODE_RIGHT_BRACKET Key code constant: ']' key. KEYCODE_RO Key code constant: Japanese Ro key. KEYCODE_S Key code constant: 'S' key. KEYCODE_SCROLL_LOCK Key code constant: Scroll Lock key. KEYCODE_SEARCH Key code constant: Search key. KEYCODE_SEMICOLON Key code constant: ';' key. KEYCODE_SETTINGS Key code constant: Settings key. KEYCODE_SHIFT_LEFT Key code constant: Left Shift modifier key. KEYCODE_SHIFT_RIGHT Key code constant: Right Shift modifier key. KEYCODE_SLASH Key code constant: '/' key. KEYCODE_SOFT_LEFT Key code constant: Soft Left key. KEYCODE_SOFT_RIGHT Key code constant: Soft Right key. KEYCODE_SPACE Key code constant: Space key. KEYCODE_STAR Key code constant: '*' key. KEYCODE_STB_INPUT Key code constant: Set-top-box input key. KEYCODE_STB_POWER Key code constant: Set-top-box power key. KEYCODE_SWITCH_CHARSET Key code constant: Switch Charset modifier key. KEYCODE_SYM Key code constant: Symbol modifier key. KEYCODE_SYSRQ Key code constant: System Request / Print Screen key. KEYCODE_T Key code constant: 'T' key. KEYCODE_TAB Key code constant: Tab key. KEYCODE_TV Key code constant: TV key. KEYCODE_TV_INPUT Key code constant: TV input key. KEYCODE_TV_POWER Key code constant: TV power key. KEYCODE_U Key code constant: 'U' key. KEYCODE_UNKNOWN Key code constant: Unknown key code. KEYCODE_V Key code constant: 'V' key. KEYCODE_VOLUME_DOWN Key code constant: Volume Down key. KEYCODE_VOLUME_MUTE Key code constant: Volume Mute key. KEYCODE_VOLUME_UP Key code constant: Volume Up key. KEYCODE_W Key code constant: 'W' key. KEYCODE_WINDOW Key code constant: Window key. KEYCODE_X Key code constant: 'X' key. KEYCODE_Y Key code constant: 'Y' key. KEYCODE_YEN Key code constant: Japanese Yen key. KEYCODE_Z Key code constant: 'Z' key. KEYCODE_ZENKAKU_HANKAKU Key code constant: Japanese full-width / half-width key. KEYCODE_ZOOM_IN Key code constant: Zoom in key. KEYCODE_ZOOM_OUT Key code constant: Zoom out key. MAX_KEYCODE This constant was deprecated in API level 3. There are now more than MAX_KEYCODE keycodes. Use
Оригинал списка: http://developer.android.com/reference/android/view/KeyEvent.html
Для моей задачи я остановился на выборе следующих команд:
Играть/Пауза adb shell input keyevent KEYCODE_MEDIA_PLAY_PAUSE Предыдущий трек adb shell input keyevent KEYCODE_MEDIA_PREVIOUS Следующий трек adb shell input keyevent KEYCODE_MEDIA_NEXT Громкость вверх adb shell input keyevent KEYCODE_VOLUME_UP Громкость вниз adb shell input keyevent KEYCODE_VOLUME_DOWN
Привожу свой юнит.pas:
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Process; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; AProcess: TProcess; implementation {$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject); begin AProcess := TProcess.Create(nil); AProcess.CommandLine := 'adb shell input keyevent KEYCODE_MEDIA_PREVIOUS'; AProcess.Options := AProcess.Options + [poWaitOnExit]; AProcess.Execute; AProcess.Free; end; procedure TForm1.Button2Click(Sender: TObject); begin AProcess := TProcess.Create(nil); AProcess.CommandLine := 'adb shell input keyevent KEYCODE_MEDIA_NEXT'; AProcess.Options := AProcess.Options + [poWaitOnExit]; AProcess.Execute; AProcess.Free; end; procedure TForm1.Button3Click(Sender: TObject); begin AProcess := TProcess.Create(nil); AProcess.CommandLine := 'adb shell input keyevent KEYCODE_VOLUME_UP'; AProcess.Options := AProcess.Options + [poWaitOnExit]; AProcess.Execute; AProcess.Free; end; procedure TForm1.Button4Click(Sender: TObject); begin AProcess := TProcess.Create(nil); AProcess.CommandLine := 'adb shell input keyevent KEYCODE_VOLUME_DOWN'; AProcess.Options := AProcess.Options + [poWaitOnExit]; AProcess.Execute; AProcess.Free; end; procedure TForm1.Button5Click(Sender: TObject); begin AProcess := TProcess.Create(nil); AProcess.CommandLine := 'adb shell input keyevent KEYCODE_MEDIA_PLAY_PAUSE'; AProcess.Options := AProcess.Options + [poWaitOnExit]; AProcess.Execute; AProcess.Free; end; end.
Чтобы в Lazarus выполнить событие по нажатию на кнопку — просто создай кнопку в редакторе форм и два раза на нее нажми — IDE пропишет событие за тебя. Чтобы собрать и выполнить написанное — F9.
http://wiki.freepascal.org/Executing_External_Programs/ru — выполнение команд из FPC
Ну вот и все, чем я хотел поделиться сегодня, удачных экспериментов.
Скачать готовое:
https://maddot.ru/share/files/1403719581_anroid_media_control.zip ~4 MB (x86_64)
Или можно воспользоваться моей утилитой Amica: https://maddot.ru/21-amica_v01_-_upravlenie_anroid_pleerom_dlya_ubuntu.html
Я в подобных случаях предпочитал делать функции-диспетчеры. Поскольку реакция на все кнопки стандартная, то и в action для всех кнопок прописываем одну и ту же процедуру.
А уже внутри нее делаем case по Sender.