简体   繁体   English

连接管理器无法在xamarin.android片段中工作

[英]Connectivity manager not working in xamarin.android fragment

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 名称getActivity在当前上下文中不存在

What's wrong with this code? 此代码有什么问题? Here's the full fragment2.cs file: 这是完整的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;
        }
    }
}

What you are doing here is the java code : 您在这里所做的是java代码:

Xamarin works on c# so getters and setters are not methods but properties: Xamarin在C#上工作,因此getter和setter不是方法,而是属性:

   ConnectivityManager connMgr = (ConnectivityManager)this.Activity.GetSystemService(Android.Content.Context.ConnectivityService);
            NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;

Goodluck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM