I'm trying to implement Bluetooth on Android, but DependencyService.Get<IBluetooth>().Test()
is throwing a NullReferenceException and I cannot figure out why. I think I'm doing everything right. My app is called MyApp. MyApp.Android references MyApp. I have a MyApp.iOS but it is only stubbed out and not set to compile.
MyApp\Home.xaml.cs:
var result = DependencyService.Get<IBluetooth>().Test(); //Debugger fails here, DependencyService.Get() is null.
MyApp\IBluetooth.cs:
namespace MyApp {
public interface IBluetooth {
bool Test();
}
}
MyApp.Android\BluetoothAndroid.cs:
[assembly: Xamarin.Forms.Dependency(typeof(BluetoothAndroid))]
namespace MyApp.Droid {
public class BluetoothAndroid : IBluetooth {
bool Test() {
BluetoothAdapter ba = BluetoothAdapter.DefaultAdapter;
if (ba == null) return false;
if (!ba.IsEnabled) return false;
return true; //Incomplete method, just for testing
}
}
}
In my searching around I see lots of warnings to "register" the service but people either never say how or say to write this:
DependencyService.Register<SampleApp.Droid.Services.AddressBook>();
but do not say where that line of code goes. Also, I have not been able to determine if the [assembly] line is a way of registering the service.
My code was originally modeled after Stack Overflow answer /a/44126899/10122542
(I can't post links) about multi-platform toast notifications which actually did work for me briefly but has not in weeks and I cannot fathom why it doesn't. DependencyService.Get<IMessage>().ShortAlert("test")
always yields a NullReferenceException!
Where is my code wrong? Thank you for your help!