android - 检查 android 中的互联网连接(不是网络连接)

标签 android android-networking internet-connection android-connectivitymanager

我在运行时检查 android 中的互联网连接时遇到问题。 我使用一些不同的方法来检查互联网连接,但我不知道哪种方法更好。因为他们每个人都有一些问题。

方法一 通过ping Google 检查互联网连接:

Runtime runtime = Runtime.getRuntime();
try {
       Process mIpAddressProcess = runtime.exec("/system/bin/ping -c 1   8.8.8.8");
       int mExitValue = mIpAddressProcess.waitFor();
       return mExitValue == 0;
} catch (InterruptedException | IOException ignore) {
            ignore.printStackTrace();
}

方法二 通过 ConnectivityManager 检查互联网连接:

public boolean checkNetwork() {

    ConnectivityManager internetManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting());

}

我在异步任务中使用方法 1,但它有时无法正常工作并且会降低应用程序的速度, 和方法 2 (ConnectivityManager) 不检查互联网连接,它只检查网络连接!

最佳答案

您可以使用下面的代码来检查网络连接是否可用。

public class NetworkConnection {
    public Context context;

    public NetworkConnection(Context applicationContext) {
        this.context=applicationContext;
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}

public class MainActivity extends AppCompatActivity {
    NetworkConnection nt_check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        nt_check=new NetworkConnection(context);
        if(nt_check.isOnline()) {
            // do logic
        } else {
            // show message network is not available.
        }
    }
}

关于android - 检查 android 中的互联网连接(不是网络连接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41545504/

相关文章:

android - 错误消息 'java.net.SocketException: socket failed: EACCES (Permission denied)'

android - 渲染期间引发异常 : View android. support.v7.widget.Toolbar 未使用正确的上下文创建

android - 有没有办法让 android 设备响应发送到广播地址的 icmp ping?

android - 移动数据开启时通过wifi(无互联网)发送数据

android - 防止用户关闭移动数据和位置

android - 如何使用 DatePicker 编辑我的日期?

android - 如何提高 OpenGL ES 中乒乓渲染(模糊)的性能

android - 在android中通信服务器网络的最佳方式和灵活方式?

sencha-touch - 确定互联网连接是否可用