在我的应用程序中,我想测试设备是否已连接到互联网并相应地运行一些代码,并且在搜索互联网后,显然以下代码应该有效:
ConnectivityManager connMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
但事实并非如此。
调试器告诉我
当前上下文中不存在名称getActivity
这段代码有什么问题?这是完整的fragment2.cs文件:
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;
}
}
}
答案 0 :(得分:2)
你在这里做的是java代码:
Xamarin适用于c#,因此getter和setter不是方法,而是属性:
ConnectivityManager connMgr = (ConnectivityManager)this.Activity.GetSystemService(Android.Content.Context.ConnectivityService);
NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;
古德勒克!