Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open setting from our application in xamarin.forms?

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?

like image 556
RMR Avatar asked Dec 19 '22 07:12

RMR


1 Answers

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.ActionLocat‌​ionSourceSettings));
    }
}

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.

like image 93
Gerald Versluis Avatar answered Jan 14 '23 22:01

Gerald Versluis