Detecting USB drive in GearVR with Unity (C#) Android application

422 views Asked by At

As the title states, I've got a Unity3D application for Samsung Gear VR and I would like to be able to detect when something is plugged into the USB-C port on the Gear.

Searching around here and on other related forums I've potentially found a way to do this with Android Intents (ACTION_USB_DEVICE_ATTACHED), but it doesn't look like that's an option for a Unity application (or at least I can't find a way to use it and the Unity forums appear to be down again).

Right now, I'm basically skipping the "detection" step, and instead have an enumerator running in the background on appropriate scenes that checks to see if any of the folders within "/storage" on Android have the subfolder named "test".Android seems to store the data from external drives in "/storage" with a folder name of seemingly-random alphanumeric characters, so the only way I've found to know for sure if it is the drive I am looking for is to check 1 layer deep to find the "test" folder.

IEnumerator DirectoryReadTest()
{
    Debug.Log("Running DirectoryReadTest...");

    while (true)
    {
        DirectoryInfo info = new DirectoryInfo("/storage");

        DirectoryInfo[] subs = info.GetDirectories();

        foreach (DirectoryInfo d in subs)
        {
            Debug.Log("Directory: " + d.Name);
            DirectoryInfo[] subd = d.GetDirectories("test");
            if (subd.Length > 0)
            {
                Debug.Log("Found a test directory in storage.");
                usbExternalDirectory = subd[0];
                break;
            }
        }
        yield return null;
    }
}

This method works for now, but means I have to have this process running constantly in the background, so it's not terribly efficient. I cannot seem to filter out the google results that are looking for things like "how to tell if android phone is plugged into computer usb", so I would appreciate any pointers in the right direction.

1

There are 1 answers

1
zambari On

While not a direct answer, two suggestions how to optimize your code: I am sure you can return WaitForSeconds(1) or (2) instead of donig the check every frame, so thats an order of 50 faster already. Secondly, DirectoryInfo is quite efficient especially on flash drives, its Debug.Log's that are cosing you cycles (each debug log does a stacktrace dump), don't ever debug.log in every frame, its one of the most underestimated performance killers