Friday, August 02, 2013

Copy whole folders from Android with only MTP to the PC (over USB, using PHP and adb)

I've always wanted my mobile phone photos to appear on my PC "magically" when I come home and have a WiFi connection. I just haven't found a decent app for this yet.

In the mean time I used to copy files with USB cable. Back in the days the phone SD card was automatically mounted as a new disk so I could automate the process with "robocopy". But ever since phones switched to MTP protocol I had no way to use batch files to copy new pictures. I guess you know the painful process of using Windows Exprorer. Mouse-oriented, choose the source folder (MTP is slow), select all files, copy, go to the destination, paste. Manual work. Programmers don't like repetitive manual work.

But then I discovered that "adb" allows to "pull" and "push" files to the device over MTP. Unfortunately it doesn't support copying whole folders. It's been several years until I discovered an "adb" command to list files on the Android device. Whow! No I can script it to copy whole folders and automatically skip files which have been already copied.

Here's the result. The script is written in PHP. You run it like this:
> php acf.php /sdcard/DCIM/100ANDRO/ ./100ANDRO/

It will read all the files in the "100ANDRO" folder on the connected device and copy missing files to the specified folder on the PC.

Requirements:
1. PHP installed.
2. Android SDK installed.
3. "USB debugging" enabled on the phone.
4. Download the script below and try.

All links contain the same source code:
http://demo.php-pastebin.com/VsY8J7m6
http://codepad.org/bYC3JLZ8
http://ideone.com/3lljIB