Reputation:
In my app I would like to test if the device is connected to the internet and run some code correspondingly, and after searching the internet apparently the following code should work:
ConnectivityManager connMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
but it doesn't.
The debugger tells me that
the name getActivity doesn't exist in the current context
What's wrong with this code? Here's the full fragment2.cs file:
using Android.OS;
using Android.Support.V4.App;
using Android.Views;
using Android.Webkit;
using Android.Net;
using Android.Widget;
using System;
namespace TabsApp.Fragments
{
public class Fragment2 : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment2 NewInstance()
{
var frag2 = new Fragment2 { Arguments = new Bundle() };
return frag2;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
View v = inflater.Inflate(Resource.Layout.fragment2, container, false);
ConnectivityManager connMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return v;
}
}
}
Upvotes: 1
Views: 962
Reputation: 16409
What you are doing here is the java code :
Xamarin works on c# so getters and setters are not methods but properties:
ConnectivityManager connMgr = (ConnectivityManager)this.Activity.GetSystemService(Android.Content.Context.ConnectivityService);
NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;
Goodluck!
Upvotes: 1