-1

Ive got this bit of code

public void TestGPS()
{
    Context context;
    var locationManager = context.GetSystemService(Context.LocationService) as LocationManager;
    locationManager.AddTestProvider("Test", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
    locationManager.SetTestProviderEnabled("Test", true);
}

Now, I cant debug my code, since the compiler marks context as "unassigned". But what would i assign context to?

THanks! :)

Alex Sorokoletov
  • 3,102
  • 2
  • 30
  • 52
user7285912
  • 201
  • 3
  • 12
  • 1
    You are not supposed to assign it, you receive context from outside. There is always a context somewhere around, you pick the correct one to use. E.g. it might be your activity or your fragment, or even [Application.Context](https://forums.xamarin.com/discussion/11102/what-is-equivalent-to-getapplicationcontext-in-xamarin-android). – GSerg Mar 26 '17 at 18:45
  • o okay.... so what would recommend changing in my code? thanks! – user7285912 Mar 26 '17 at 18:52
  • You pick the context that is better for that method and pass it as a parameter (if the method is somewhere unrelated), or use the hosting activity/fragment as context directly (if the method is inside an activity/fragment). – GSerg Mar 26 '17 at 18:55

1 Answers1

2

Passing/requiring Context is very common in Android.

Usually that means you have to pass reference to current activity. That will be this inside any activity, this.Context inside fragment.

If you want to use this code inside some service that has no clue about UI/activities, common suggestion is to pass context to the service initialization and then store a reference to this context. Be careful as this might lead to memory leaks (you will be storing a reference to an activity and will be keeping it alive).

Alternatively, you can use so called current context: Android.App.Application.Context.

In your case, if this is a part of Activity code, you have to change it to:

public void TestGPS()
{
    var locationManager = this.GetSystemService(Context.LocationService) as LocationManager;
    locationManager.AddTestProvider("Test", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
    locationManager.SetTestProviderEnabled("Test", true);
}

If this is a part of a service (non-UI), then:

public void TestGPS()
{
    var context = Android.App.Application.Context;
    var locationManager = context.GetSystemService(Context.LocationService) as LocationManager;
    locationManager.AddTestProvider("Test", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
    locationManager.SetTestProviderEnabled("Test", true);
}

Some good articles on the topic:

Xamarin: Android Activities, Context, Intents and Views

What is Context on Android

Community
  • 1
  • 1
Alex Sorokoletov
  • 3,102
  • 2
  • 30
  • 52