0

I am getting the following error when trying to open GPS settings page if GPS is not enabled (within Xamarin):

Unknown identifier: StartActivity

Unhandled Exception:

Java.Lang.NullPointerException:

Can somebody please guide where am I getting wrong?

This My Interface

namespace MyApp
{
    public interface GpsSettings
    {
        void showGpsSettings();
    }
}

This the Implementation

[assembly: Xamarin.Forms.Dependency(typeof(GpsSettingsImplementation))]
namespace MyApp.Droid
{

    public class GpsSettingsImplementation : Activity, GpsSettings
    {
        public GpsSettingsImplementation()
        {

        }


        public void showGpsSettings()
        {

            var intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
            StartActivity(intent);
        }
    }
}

This is how I call my function on button click

 DependencyService.Get<GpsSettings>().showGpsSettings();
A. Sinha
  • 2,666
  • 3
  • 26
  • 45

1 Answers1

0

An existing Activity instance has a bit of work that goes on behind the scenes when it's constructed; activities started through the intent system (all activities) will have a Context reference added to them when they are instantiated. This context reference is used in the call-chain of StartActivity.

So, the Java.Lang.NullPointerException seen after invoking StartActivity on your Test activity instance is because the Context inside that instance has never been set. By using the new operator to create an activity instance you've circumvented the normal way activities are instantiated, leaving your instance in an invalid state!

ref: https://stackoverflow.com/a/31330999/5145530

The above error can be resolved in the following manner:

[assembly: Xamarin.Forms.Dependency(typeof(GpsSettingsImplementation))]
namespace MyApp.Droid
{
    public class GpsSettingsImplementation : Activity, GpsSettings
    {
        public GpsSettingsImplementation()
        {

        }


        public void showGpsSettings()
        {

            var intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
            intent.SetFlags(ActivityFlags.NewTask);
            Android.App.Application.Context.StartActivity(intent);

        }
    }
}
Community
  • 1
  • 1
A. Sinha
  • 2,666
  • 3
  • 26
  • 45