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.
In Android I use this (calling with DependencyServices) to open Settings
public void View(){
LocationManager locationManager = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);
if (locationManager.IsProviderEnabled(LocationManager.GpsProvider) == false)
{
Intent gpsSettingIntent = new Intent(Settings.ActionLocationSourceSettings);
Forms.Context.StartActivity(gpsSettingIntent);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.