There is a particular issue when writing any code which will run on Android which presents external UI through an Intent or uses broadcasts in that you need to have a reference to the current Activity. I covered this in my last post.
Following on from that I moved the code to a new library (since it is required in both the Bluetooth Classic and Bluetooth LE libraries). It now provides a simple API which you can use to determine the current Activity without adding any framework dependencies.
InTheHand.AndroidActivity.CurrentActivity
The code can determine this on Xamarin Forms, .NET MAUI and Uno Platform. I haven’t figured out if there is a clean way to do this on Avalonia yet but there is a simple workaround for everything currently unsupported – including if you want to use the libraries from “native” Xamarin Android or .NET 6.0 Android and beyond.
Every Android project contains a main Activity. For an Avalonia mobile app this is in MainActivity.cs and is an empty class derived from AvaloniaMainActivity. Simply override the OnCreate method like so:-
protected override void OnCreate(Bundle savedInstanceState)
{
// provide reference to current activity
InTheHand.AndroidActivity.CurrentActivity = this;
base.OnCreate(savedInstanceState);
}
Note that to use Bluetooth you also need to add code to your activity to request permission but I’ve excluded this for clarity. So now InTheHand.Net.Bluetooth 4.0.34 and InTheHand.BluetoothLE 4.0.33 are fully supported on Avalonia or any native .NET projects.
You can reuse this logic yourself using the InTheHand.AndroidActivity NuGet package. I’ll keep it updated to support any new or updated frameworks.