Android Check Internet Connection Android 8.0

问题描述 投票:1回答:1

我在Android 5-7中成功使用此方法来检查我的设备是否具有Internet连接:

public bool CheckInternet()
{
    bool checkInternet = false;
    Ping ping = new Ping(); 
    try
    {
        PingReply reply = ping.Send("www.google.de", 100);
        if (reply != null) checkInternet = reply.Status == IPStatus.Success;
    }
    catch (Exception e)
    {
        checkInternet = false;
    }
    return checkInternet;
}

无论出于何种原因,此方法对Android 8都不起作用。它始终返回false。

这可能是什么原因?

编辑:

我不寻找另一种解决方案,我已经有了适用于Android 8(和7,6 ......)的工作解决方案。我在寻找原因,为什么

checkInternet = reply.Status == IPStatus.Success;

在Android 8设备上返回false。

android xamarin.android connection connectivity
1个回答
0
投票

首先创建一个可以测试网络状态的类,如下所示:

    import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;
import com.gstech.merge.disasterapp.activities.MainActivity;
public class NetStatus {
    Context mCtx;
    public NetStatus(Context mCtx) {
        this.mCtx = mCtx;
    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

现在创建类的对象,并从上下文的任何位置检查网络状态。

NetStatus status = new NetStatus(MainActivity.this);
if (status.isNetworkAvailable()){
    Toast.makeText(mCtx, "Internet Available", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(mCtx, "Internet Not Available", Toast.LENGTH_SHORT).show();
© www.soinside.com 2019 - 2024. All rights reserved.