Hi there
I want to be able to see when a user has mounted/removed an external drive from an android app. (It will primarily be a USB device).
I want to be able to only save data to the USB and not on the device itself.
I thought I would see if a device is mounted and if it is use the provided drive. If no device is found and the user attempts to save, then display an error asking them to plug a drive in.
Trying to find the directory for removable storage on android has proven more difficult then anticipated.
I have created an ActionMediaMounted broadcast receiver, but it never fires.
I have also created an ActionPowerConnected and ActionsPowerDisconnected broadcast receiver and these also don't seem to fire.
I figure I am probably missing some kind of permission or manifest update.
Below is an example of the Action power broadcast receiver.
[BroadcastReceiver(Enabled = true, Exported = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionPowerConnected, Android.Content.Intent.ActionPowerDisconnected })]
public class PowerConnectedBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
}
}
This is my broadcast receiver for the device mounted:
[BroadcastReceiver(Enabled = true, Exported = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionMediaMounted})]
public class ExternalStorageBroadcastReceiver : BroadcastReceiver
{
private static string TAG = "ExternalStorageBroadcastReceiver";
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, $"USB plugged in fired", ToastLength.Long).Show();
string action = intent.Action;
if (!string.IsNullOrEmpty(action))
{
Log.Info(TAG, $"got action which is :{action}");
Toast.MakeText(context, $"got action which is :{action}", ToastLength.Long).Show();
}
else
{
Log.Info(TAG, "no action has been found");
Toast.MakeText(context, $"no action has been found", ToastLength.Long).Show();
}
if(Android.Content.Intent.ActionMediaMounted.Equals(action))
{
Log.Info(TAG, $"Received media mounted : {action}");
Toast.MakeText(context, $"Received media mounted : {action}", ToastLength.Long).Show();
if (intent != null && intent.Data != null)
{
string mediaPathLocation = intent.Data.Path;
if(!string.IsNullOrEmpty(mediaPathLocation))
{
Log.Info(TAG, $"The media uri location is : {mediaPathLocation}");
Toast.MakeText(context, $"The media uri location is : {mediaPathLocation}", ToastLength.Long).Show();
}
}
}
}
}
I read the documentation from android that said some system broadcasts would be stopped, but there is a list of excluded and the mediamounted is within that
https://developer.android.com/guide/components/broadcast-exceptions
The toasts do not display on my device.
Any ideas would be appreciatd.
Many thanks