Eman44
Eman44

Reputation: 21

How to differentiate SD card and External Hard Drive storage paths on Android Xamarin?

My tablet has an SD card and external hard drive. I am calling GetExternalFilesDirs to get all shared/external storage devices where the application can place persistent files it owns.

Here is my code:

var ctx = Android.App.Application.Context;
Java.IO.File[] storagePaths = ctx.GetExternalFilesDirs(null);

storagePaths contains 3 files:

  1. /storage/emulated/0/path_to_app_data (emulated storage)
  2. /storage/0123-4567/path_to_app_data (SD card)
  3. /storage/285B-DFC6/path_to_app_data (USB hard drive)

How could I programmatically confirm which one of these (path 2 or path 3) is the USB storage device?

Upvotes: 0

Views: 368

Answers (1)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13861

The path for mounting a USB device to an Android device varies with Android devices from different vendors.

You can register a BroadcastReceiver to listen to the mounted event in your app. Once the USB hard drive is mounted with the android device, we can recieve a BroadcastReceiver.

And in the BroadcastReceiver ,we can get the path of the of the USB hard drive. Once we get the path of the hard storage, we can distinguish which path is the one we need.

You can refer to the following code snippet:

public class USBBroadCastReceiver : BroadcastReceiver
{
    string TAG = "USBBroadCastReceiver";
    public override void OnReceive(Context context, Intent intent)
    {

        String action = intent.Action;

        if (Intent.ActionMediaMounted.Equals(action))
        {

                UsbDevice device = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice);

                if (intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false)) 
                { 

                    if (device != null)
                    {
                        // call method to set up device communication

                        Log.Debug(TAG, "onReceive: " + intent.Extras.ToString());
                        Log.Debug(TAG, "onReceive: " + intent.Data);

                        // here you can get the path of your USB hard drive
                        String path = intent.Data.Path;

                        Log.Debug(TAG, "onReceive: path of device received from intent: " + path);

                    }
                }

        }
    }

Upvotes: 0

Related Questions