Search code examples
androidxamarinbroadcastreceiver

Xamarin Android, detecting USB drive connection


I'm using Visual Studio 2015 and Xamarin and I'm trying to detect when a user inserts an USB drive in an android app.

This is my BroadcastReceiver implementation.

 [BroadcastReceiver(Enabled =true)]
[IntentFilter(new[] { Intent.ActionMediaMounted })]
class DeviceMonitor : BroadcastReceiver, IDeviceMonitor
{
    public override void OnReceive(Context context, Intent intent)
    {
        if (DeviceAdded != null)
            DeviceAdded(this, new EventArgs());

        if (intent.Action.ToLower() == "android.intent.action.ums_connected")
        {
            Java.IO.File[] files = context.GetExternalMediaDirs();
        }
    }
}

The receiver is registered at the MainActivity in the OnCreate method

DeviceMonitor monitor = new Classes.DeviceMonitor();
        RegisterReceiver(monitor, new Android.Content.IntentFilter(Intent.ActionMediaMounted));

This is my AndroidManifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="WebView.CrossPlatform.Server.Droid" android:versionCode="1">
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
<application android:label="WebView.CrossPlatform.Server.Droid">
    <receiver android:name=".Classes.DeviceMonitor" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_MOUNTED" />
            <data android:scheme="file" />
        </intent-filter>
    </receiver>
</application>

But this does not seem to work. I've looked for solutions and tried about everything that I could find, but nothing is working.

Can anyone see what I'm doing wrong ?

Thanks,


Solution

  • I found the problem. As it turns out I don't need to change the manifest by hand. By adding attributes to my classes the manifest is automatically generated. It works now by using the "android.intent.action.MEDIA_MOUNTED" action.