Eject / Unmount USB Programmatically

1.6k Views Asked by At

I am developing an Android Application in Xamarin where I listen to USB devices connected to my Android Device via OTG. I have been successful in listening to the USB devices connecting to my Android Device through BroadcastReceiver.

I am stuck on 2 places :

  1. The moment I get to know that a device has been connected, I want to disconnect it programmatically. This is for security reasons.

  2. Although I am able to detect the USB devices, the receiver seems to have gone Global. That is , even if my app is not running in the background and if I connect a USB device through OTG, the BroadcastReceiver listens to it. I don't want that to happen.

I searched a lot of sites but was not able to find any help regarding eject/unmounting programmatically.

This is what I have done so far :

   UsbDetection usbDetection;

    protected async override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        usbDetection = new UsbDetection();

        IntentFilter filter = new IntentFilter("android.hardware.usb.action.USB_STATE");
        RegisterReceiver(usbDetection, filter);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }

[BroadcastReceiver(Enabled = true, Exported = false)]

[Android.App.IntentFilter(actions: new[] {"android.hardware.usb.action.USB_STATE", "android.hardware.usb.action.USB_DEVICE_ATTACHED", "android.hardware.usb.action.USB_DEVICE_DETACHED"})]

public class UsbDetection : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        string action = intent.Action;
        Console.WriteLine(action);
        Toast.MakeText(Android.App.Application.Context, action, ToastLength.Long).Show();

        if(action.Equals("android.hardware.usb.action.USB_DEVICE_ATTACHED"))
        {
            UsbDevice device = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice);

            if(device!=null)
            {
                Programmatically eject/unmount the usb device. 
            }
        }
    }
}

Any suggestions regarding this will be helpful.

0

There are 0 best solutions below