首页 > 解决方案 > 如何检查设备是否刚刚连接到互联网

问题描述

有没有办法检查尚未连接到 Internet 的设备何时刚连接。如果我在我的应用程序中将手机连接到 Internet,我应该执行一些操作(例如Toast)。

注意:Detect if Android device has Internet connection Android - checks if the device is connected to the internet不是同一个问题。

标签: android

解决方案


尝试这个:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

您还需要:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在你的 android 清单中。

请注意,拥有活动的网络接口并不能保证特定的网络服务可用。


推荐阅读