android - 如何检查设备是否刚刚连接到互联网
问题描述
有没有办法检查尚未连接到 Internet 的设备何时刚连接。如果我在我的应用程序中将手机连接到 Internet,我应该执行一些操作(例如Toast
)。
注意:Detect if Android device has Internet connection 和Android - checks if the device is connected to the internet不是同一个问题。
解决方案
尝试这个:
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 清单中。
请注意,拥有活动的网络接口并不能保证特定的网络服务可用。
推荐阅读
- vuejs2 - 换页时 Nuxt JS 页面内容闪烁
- opencv - Plt 绘制到 OpenCV 图像/Numpy 数组
- kubernetes - 我可以用原生 kubernetes 消息队列替换 RabbitMQ
- sql - 从列中统计 7 和 0 出现的次数
- flutter - 被键盘覆盖的底板
- java - 我如何将证书与 JAVA 中的 CSR 相匹配
- authorization - 在 XACML 2.0 策略中评估多值属性
- django - 如何为随机网址创建视图?
- javascript - 为什么 Rxjs 在订阅回调中出错时取消订阅?
- ruby - 使用 Ruby 和 Bing Ads API v2.0 的任何示例?