I am working on xamarin.forms. (Facing below problem only in android)
When my application is started it checks my GPS location is on or off.
To check GPS location on or off I am using dependency service.
public static bool CheckGPSConnection()
{
var gpsConnection = DependencyService.Get<IGPSConnectivity>();
return gpsConnection.CheckGPSConnection();
}
When I come to Home page of my application I put following code
if (Device.OS == TargetPlatform.Android)
{
if (!App.CheckGPSConnection())
{
bool answer = await DisplayAlert("Alert", "Would you like to start GPS?", "Yes", "No");
if (answer)
{
Android.App.Application.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings));
}
}
}
but it's giving me an exception
{Android.Util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/…}
What should I do?
This is platform specific functionality, so you should create a DependencyService for it.
Just like for the IGPSConnectivity
create another interface. For example ISettingsService
.
public interface ISettingsService
{
void OpenSettings();
}
Then on Android, implement it like this:
public class SettingsServiceAndroid : ISettingsService
{
public void OpenSettings()
{
Xamarin.Forms.Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings));
}
}
Now call it from your shared PCL code, again, just like with the GPS connectivity one.
DependencyService.Get<ISettingsService>().OpenSettings();
Because you are using the DependencyService, the right implementation per platform will be injected. So, there is no need for the if (Device.OS == TargetPlatform.Android)
line, unless you did that for another reason of course. Also, I think this method is now deprecated. You should now use Device.RuntimePlatform == Device.Android
as of Xamarin.Forms 2.3.4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With