Connect to android from pc usb

Работа с устройствами USB в Android

В недавней статье на Geektimes в комментариях возник вопрос о поддержке в ОС Android периферии, подключенной к шине USB. Действительно, большинство вендорского ПО, к примеру, для работы с принтерами и МФУ, поддерживает только подключение по сети. Однако это не означает, что в самой ОС Android нет такой возможности — это означает лишь то, что большинство устройств не имеют полноценного USB хоста, и далеко не все имеют поддержку OTG. По сети же могут работать абсолютно все без исключения.

Большинство устройств на Android при наличии порта OTG поддерживают на уровне системы (ядра Linux или стандартных компонентов Android) следующие классы устройств:

  • Устройства ввода — клавиатуры, мыши, джойстики (HID)
  • Накопители (Mass Storage)

Несколько реже:

  • Сотовые модемы
  • Сетевые адаптеры
  • Вебкамеры

Хабы поддерживаются при наличии полноценных хост-портов, но не поддерживаются на портах OTG.

Подробнее список устройств, поддерживаемых на уровне ядра Linux, можно получить в sysfs:

$ ls /sys/bus/usb/drivers

Если же модуль в принципе доступен в исходниках ядра Linux, но не включен в Android — не стоит рассчитывать на то, что его получится собрать и расставить на все целевые системы.

Однако, начиная с Android 3.1 (API 12), в системе содержатся средства, достаточные для поддержки на уровне приложения любой USB периферии. Данные средства описаны в разделе USB Host руководства по Android API. Здесь же я хочу привести примеры реальной работы с некоторыми видами устройств.

Права доступа

Как и для прочих действий, Android требует, чтобы приложение получило разрешение на доступ к USB периферии. Существует 2 способа получить такое разрешение:

  • Задекларировать список устройств в AndroidManifest
  • Явно показать пользователю диалог “разрешить”

Поскольку для моих задач лишние вопросы к пользователю были нежелательны, я использовал первый способ.

Итак, нам необходимо добавить в манифест следующее:

А в res/xml/device_filter.xml вписать следующее:

Отмечу, что хотя общепринято указывать VID:PID в 16-ричной системе счисления, здесь они должны быть указаны в десятичной. В документации заявляется, что возможно указание только класса, без VID и PID, но у меня это не стало работать.

Принтеры

На примере принтера я покажу, как непосредственно использовать API android.hardware.usb. На уровне передачи данных все принтеры поддерживают стандартый класс USB устройств:

Читайте также:  Удаленное управление андроид телефоном с компьютера через usb если

Класс предельно простой. В рамках этого класса устройство должно поддерживать:

  • Обязательный bulk out endpoind для отправки данных на принтер
  • Опциональный bulk in endpoind для получения статуса принтера
  • 3 управляющих запроса

Код, приведенный ниже, предоставляет функциональность, аналогичную устройству /dev/usb/lp в Linux. Далее нам нужен фильтр, преобразующий исходный документ в пакет данных, понятный конкретной модели принтера. Но это тема иной статьи. Как один из вариантов — можно собрать ghostscript с помощью NDK.

Для работы с устройством нам в первую очередь нужно:

1. Найти устройство. В примере для простоты я ищу первый попавшийся:

2. Получить endpoint’ы:

3. Непосредсвенно открыть устройство:

4. После этого мы можем читать и писать в устройство:

5. По завершении работы — закрыть устройство:

Преобразователи USB-Serial

В отличие от притеров, преобразователи USB-Serial гораздо менее стандартизированы. Существует несколько распространенных чипов, для которых существенно отличается установка параметров последовательного порта — битрейта, чётности и проч. К счастью, есть библиотека github.com/mik3y/usb-serial-for-android, поддерживающая практически все существующие чипы. Библиотека полностью скрывает USB API, сводя все необходимые действия к минимуму вызовов с минимумом параметров.

1. Найти и открыть устройство:

2. Установить параметры последовательного порта:

3. Читать и писать в порт:

4. По завершении работы — закрыть порт:

Резюме

Надеюсь, что мне удалось показать, что работа с USB периферией достаточно проста и логична. Безусловно, реализация протоколов некоторых конкретных устройств не блещет простотой — но это проявится в любой системе в одинаковой степени.

Все приведенные примеры я взял из реального проекта, лишь исключил очевидные проверки, оставив только ключевые строки.

Источник

How to Connect an Android to a PC

Corded and wireless options to connecting your phone to your computer

What to Know

  • Connect the devices with a USB cable. Then on Android, select Transfer files. On PC, select Open device to view files >This PC.
  • Connect wirelessly with AirDroid from Google Play, Bluetooth, or the Microsoft Your Phone app.

This article explains how to connect an Android to a PC by using a USB cable or a wireless connection via AirDroid, Bluetooth, or the Microsoft Your Phone app.

How to Connect an Android to a PC

If you want to connect an Android to a PC, there are several options. The most common approach is to use a USB cable, but there are a number of wireless solutions that’ll work just as well, and often offer a faster connection.

Most Android devices come with a USB charging cable, with the charger end connected via the USB end of the wire. If you unplug the USB end from the charger, you can plug that end into your PC to initiate a connection with your computer.

Читайте также:  Калибровка отпечатка пальца samsung a50 11 андроид

However, if you don’t have your USB cable with you, or prefer a wireless solution, these are the ways you can connect an Android to a PC without a cable:

  • Using AirDroid: This popular app uses your home network to establish a connection between your computer and Android device and transfer files.
  • Bluetooth: Most modern computers have Bluetooth available. You can use Bluetooth to transfer files from your Android.
  • Microsoft’s Your Phone App: Microsoft now offers a new app for Windows 10 users called Your Phone, which provides an easy connection with your Android.

Connect an Android to a PC With USB

Using a USB cable to connect your Android to your PC is easy, but it only allows you to transfer files back and forth. You can’t remotely control your Android using this connection.

First, connect the micro-USB end of the cable to your phone, and the USB end to your computer.

When you connect your Android to your PC via the USB cable, you’ll see a USB connection notification in your Android notifications area. Tap the notification, then tap Transfer files.

On your computer, you’ll see a notification asking what you’d like to do with the new USB device. Select this notification.

This will open a window to select how you’d like to use the device. Select Open device to view files.

Now, when you open Windows Explorer, select This PC and you’ll see your device available. Select the device to expand it and browse through all of the folders and files on your phone.

Connect an Android to a PC With AirDroid

AirDroid is an impressive app because it allows you to not only transfer files to and from your Android, but it also includes a number of remote control features.

Install AirDroid from Google Play onto your Android device.

Open the app and enable the features you plan to use. You may need to create a new AirDroid account if this is the first time you’re using the app.

Some features, such as remotely controlling your Android screen, requires root access to the device. Additionally, some features are disabled unless you purchase the Premium plan.

Visit AirDroid Web, and log into the same account you created above.

Once you connect, you’ll see the main dashboard. On the right, you’ll see a toolbox with a summary of information about your phone storage. On the left, you’ll see all of the apps that let you control your phone.

Читайте также:  Уменьшить интенсивность вибрации андроид

Select the Files app to browse files on your phone and transfer files back and forth.

Select the Messages app to review stored messages on your phone or to launch a new SMS session with anyone in your contacts list.

You can even use the Camera app to remotely view and control the camera on your Android phone.

Connect an Android to a PC With Bluetooth

If you only need a connection to transfer files, bluetooth is an excellent option because it requires no wires and the transfers are fast and easy.

Make sure bluetooth is turned on for both your Android device and your computer. When it is, you’ll see the computer show up on your Android as an available device to pair with.

Tap this device to pair with it. You should see a pair code appear on both the PC and on your android device. Tap Pair to complete the connection.

Once connected, on your PC right-click the bluetooth icon on the right side of the taskbar, then select either Send a File or Receive a File.

Next, browse to the file on your PC that you want to transfer and select Next.

This will initiate the file transfer from your PC to your Android.

Connect an Android to a PC With Microsoft Your Phone

Another convenient cloud bases service that’ll let you access your phone’s files, texts, and notifications is a new service provided by Microsoft called Your Phone.

The Your Phone app is ideal for those situations when you’ve forgotten your phone at home. From your laptop, you can still see all messages and notifications you might have otherwise missed.

Install the Microsoft Your Phone app from Google Play onto your Android. You’ll need to accept all of the requested security permissions.

Install the Your Phone app from the Microsoft Store onto your Windows 10 PC.

Launch the Your Phone app on your computer and select Android as the phone type that you want to connect to. Then select Get started.

Your computer will connect to your Android phone. Select Photos from the left panel to view all photos on your phone.

Select Messages to view messages, or send and receive new messages, from your computer through your Android phone.

Select Notifications to view all recent notifications on your Android phone.

Источник

Оцените статью