在我的应用程序中,我想测试设备是否已连接到互联网并相应地运行一些代码,并且在搜索互联网之后,以下代码显然应该可以工作:
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;
}
}
}
慕慕森
相关分类