Usb file transfer android phone

Работа с устройствами 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 устройств:

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

  • Обязательный 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 периферией достаточно проста и логична. Безусловно, реализация протоколов некоторых конкретных устройств не блещет простотой — но это проявится в любой системе в одинаковой степени.

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

Источник

Fixed! Android USB File Transfer Not Working Issue

If you have a need to transfer your files from your Android device to your desktop computer, you can make these transfers with ease. Since users transfer their files on a regular basis now, these processes have been simplified. In fact, with only a few basic steps and the proper tools, you can have everything on your android device transferred to your desktop without a hassle. In fact, most people will find that this process is simple to do, and they do not need a lot of technical savvy experience to transfer all of their files over.

Читайте также:  Usb option on android

Part 1: How to Transfer Android Files via USB

Having said that, here are the steps that you will need to complete the transfer process successfully.

Step 1. Make sure that you have all of the essential resources in one centralized place before beginning this task. You will need your Android device, your desktop computer, and a USB cable.

Step 2. Once you have all of these resources in place, the next step in this process is to decide what you want to transfer. This is because you will have the capability to do the following types of transfers:

— Transfer your files from and to both Android external and internal storage and your desktop
— Transfer your files from your external storage to your external storage on an android phone and an android tablet.
— Transfer all of your files from one or more Android devices to other Android devices, including the most commonly used, your Android phone to your Android tablet.

Therefore, with this step, you can pick and choose which one that you want or need to do.

Step 3: To transfer the files that you need to place on your desktop, you should make sure to plug your USB cable into your android device, and the other end of this cable into your desktop’s USB port.

Step 4: When the connections to both are secured, the next step is to double click on the device’s icon on your desktop so that you can view the files that you want to transfer. You will have the option of choosing specific files one by one or you may want to select all of your files at once. In either case, once you make your selections, you can begin the transfer process.

Step 5: When this transfer process is completed, you can create a new folder that you can drag and drop all of the files into. This step is up to you and your needs.

Part 2: Solutions for Android USB File Transfer Not Working

When transfers are being made, the user can experience several different kinds of problems before the transfer is complete. So, it is essential for the user to know what to expect if all of the files do not go over as planned. Here are some of the most common problems that a user can encounter when they have initiated the transfer process.

1. USB cable comes detached from the desktop computer or from the Android device during the transfer process. When this occurs, the process for the transfer will not be complete and the user will receive a message that tells them that this has occurred.

2. The files are out of sync. When files are out of sync the dates may be out of order so it may be difficult to find text messages that were sent doing a specific period of time.

3. File transfer is only partially complete because there is not enough file space on the desktop to store all of the information that is being transferred.

4. Files lost in the transfer and need to be recovered to ensure that they are stored on both the android phone and the desktop computer.

5. Some of the data files can be corrupted during the transfer so they cannot be opened by the user.

Part 3: Alternative to Android USB File Transfer

Though there are many different ways to transfer files from one Android device to your desktop, some of the options tend to be a lot better than others. Specifically, when you are considering using Coolmuster Android Assistant (for all Windows versions) or Coolmuster Android Assistant for Mac (for all Mac versions) to make your transfers. It is able to transfer and manage Android contacts, SMS, call logs, photos, videos, music, apps and more on computer. Android Assistant is one of the most notable and best alternative for these kinds of activities.This is because this software will allow you to make your transfers in no more 2 to 3 steps at most.

Step 1. Connect your Android phone with your computer

Download and install Android Assistant on your computer. Launch it and use a USB cable to connect your Android device to your computer. (You may have to open USB debugging on Android phone before Android Assistant can open and read all your phone data)

Читайте также:  Андроид как выключить гугл ассистента

Once your connected Android phone is detected by the program, a screen will pop up with all the data categories of your smartphone on the left hand side column and an icon for your smartphone in the middle.

Step 2: Transfer Android phone data to computer

As you can see, all transferable file types are listed on the left side menu. Just choose the data type you want to transfer and click the option of «Export» from the top menu. Then you’ll be able to specify an output location on your computer and save all the transferred data here.

Once these steps have been completed, the user does not have to be concerned about files being lost, out of sync, and or encountering any othetechnicalal problems when being done. So, it is a great way to make transfers without experiencing issues that interrupt the successfulness of these transfers.

Источник

10 Best Android File Transfer Apps to Transfer Data from Android to Android

Are you tired of looking for easy and simple ways to transfer files between Android devices? We are going to solve that problem with the best file transfer apps for Android that you can use to move files between Android phones and other devices. All the apps are free to use and take help of WiFi, hotspot or Bluetooth to send and receive data.

The Top 10 Amazing Android File Transfer Apps for You

So here are the top 10 file sharing apps for Android!

1. Shareit

Shareit is one of the most popular Android file transfer applications used by over 500,000,000 people across the world. It has a rating of 4.6 on the Google Play Store and countless reviews left by satisfied users.

You can transfer any type of files such as movies, documents, songs, pictures, apps and more using the app. It lets you transfer files without any loss of quality at speeds 200 times faster than regular Bluetooth. You can get speeds up to 20 MB/sec to send large files in a matter of minutes.

The app uses 5 GHz hotspot mode to transfer files in Android 6.0, 7.0 and 7.1. This feature is not supported by Android 8.1 and above versions.

2. Xender

Xender is another useful Android file transfer app with more than 500 million users. You can transfer all types of files without restriction over a hotspot connection that doesn’t require any wires, cables or data connection. The app can also be used for cross-platform data transfers between phone and a PC or Mac and Android, Windows and iOS operating systems.

Xender can achieve speeds up to 40 MB/sec enabling you to transfer files of any sizes without restrictions. You can also transfer mobile data like pictures, messages, contacts, games, music, and videos from your old phone to a new one using one simple step. It also comes with a file manager to view, move or delete your files.

3. Send Anywhere

Send Anywhere is one of the best file sharing apps for Android that protects your data with strong 256-bit encryption. To transfer a file, you have to enter a one-time six-digit key for security purposes.

You can transfer any files between Android phones without taking help of internet or mobile data. It also allows you to send files to multiple people at once using a custom link.

Users can also go for Send Anywhere Plus where they can send 50 GB of content at a single time. You can also set expiration dates and limit the download count as per your convenience. The Android data transfer app is really useful when you need to transfer files in a hassle-free way.

4. Zapya

Zapya Android file transfer app lets you instantly send data to phones located nearby. You can create a customized QR scan code that others use to connect to your device securely. The app allows you to send files to a group of people and chat with them using the instant messenger feature. You can create your own group and invite others to join in!

The app also comes with a phone replication option which is helpful to backup and transfer files from old phone to a new one. You can also use it to backup your phone data on a PC or Mac.

5. AirDroid

AirDroid lets you do more than just transferring data from Android to Android. You can use it to control your phone using your computer and even access apps like WhatsApp and WeChat on your PC. It has also been recommended by various tech websites such as CNET, Lifehacker, BGR and PCWorld.

Читайте также:  Top темы для андроид

AirDroid Android file transfer app enables you to backup files from phone to computer while you can share clipboard between the two devices. You can also control your phone through your PC using the mouse and the keyboard. It also allows you to manage your videos, ringtones, and photos by uploading and exporting them.

Special Recommendation – Gihosoft Mobile Transfer

Gihosoft Phone Transfer app helps you transfer files using three simple steps- connect the phones, select the files to transfer and share them! You can transfer photos, videos, call logs, contacts, SMS, music and more from Android to Android, Android to iPhone, Android to Mac/PC, iPhone to iPhone, iTunes to Android and more.

You can take help of the app to backup your data to a computer and restore them on any Android or iOS device. The solution is 100% safe and compatible with a wide range of Android and iOS models. Best of all, the app is entirely free to try!

6. SuperBeam

SuperBeam file transfer app uses WiFi direct mode to share large files. When WiFi direct is not available, it can switch over to hotspot or local network to transfer data. You can share multiple types of files by pairing devices through a QR code, NFC and manual keys.

The Android file transfer app also allows you to share files to phones that don’t have SuperBeam using a web interface. It comes with a user-friendly interface with simple send and receives actions. There’s also no need to worry about duplicate items as they are given unique titles. You can also view the history of all transferred data.

7. WiFi File Transfer

WiFi File Transfer can send or receive files over a local WiFi connection. You can share files between phones, tablets, and computers. All devices should be on the same network for this Android data transfer app to work.

You can download or upload multiple files simultaneously and even transfer entire folder structures in case of Google Chrome. The file manager in the app lets you view, delete, edit, zip and unzip files all from the same interface. You can also set up a password authentication to ensure the right devices are connected.

The only drawback of the app is that it only lets you transfer files up to 5 MB.

8. Samsung Smart Switch

Samsung Galaxy users will find this to be the best file sharing app for Android. It supports Galaxy handsets along with some other non-Samsung Android models. The app is preloaded in some Galaxy models such as S7, S8, S9, Note 8 and Note 9 and lets you transfer contacts, calendar, music, photos, text messages and more.

You can also use the charger cable and USB connector to share files using a wired method. The app also enables you to pair devices of other platforms like iOS, Windows, and Blackberry.

9. Mi Drop

The ad-free P2P file transfer app comes from Xiaomi and is pre-installed in Mi phones. All Android devices can take advantage of this fast and simple file transfer method without restrictions.

You can move files without the need of an internet connection. The files are sorted in different categories making it easy to find and search them. The transfer speed can reach up to 50 MB/sec, making it almost 200 times faster than Bluetooth. There are no complicated steps, and you can share files with a single tap!

The app also doesn’t put any limitations on the file size- you can send or receive as much as you want.

10. Bluetooth File Transfer

You can share files over a Bluetooth connection using this Android data transfer app. It provides a secure way to transfer your data as you can authorize all the incoming connections. One unique advantage of this app is that it can use infrared to connect to old cell phones such as LG, Nokia, Samsung, and Sony.

The app has an inbuilt fast file browser and features a clean and fast UI. You can also use the integrated explorer to cut, move, copy and delete items. It can also perform zip and unzip of files with encryption.

So, which of these Android file transfer apps is your favorite? Let us know in the comments below.

Bonus Tip: If you need to restore deleted or lost files from your Android device, this Free Android Data Recovery Software can help you quickly get them back.

Источник

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