Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Eject / Unmount USB Programmatically.

I am developing an Android Application 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 BroadcaseReceiver listens to it. I don't want that to happen.

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 help regarding this will be helpful.

Sign In or Register to comment.