android - Android 在电量不足时检查连接(省电模式)
问题描述
我尝试了以下代码来检查连接性:
public static NetworkInfo getNetworkInfo(Context context) {
if (context == null)
return null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected())
return activeNetwork;
else {
for (Network n: cm.getAllNetworks()) {
NetworkInfo nInfo = cm.getNetworkInfo(n);
if(nInfo != null && nInfo.isConnected())
return nInfo;
}
}
return activeNetwork;
}
public static boolean isConnectivityAllowed(Context context) {
NetworkInfo info = NetworkUtils.getNetworkInfo(context);
return info != null && info.isConnected();
}
通常,它工作正常,但在某些情况下,尽管我有连接,但它返回断开连接。经过搜索,测试,检查日志,我了解到如果我运行该应用程序的设备电池电量不足,该功能返回断开连接,因为操作系统将系统置于省电模式,然后如果我更改连接,应用程序会得到正确的答案. @phil 的答案中提供了更多信息。
有谁知道开启节电时如何检查连接?!
解决方案
在 AndroidManifest.xml 中添加以下权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
为连接检查创建一个 NetworkUtils 类
public class NetworkUtils {
/**
* Check if mobile data is enabled
*
* @return mobile data on or off
*/
private static boolean isMobileDataEnabled(Context context) {
Context ctx = context.getApplicationContext();
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
return (Boolean) cm.getClass().getMethod("getMobileDataEnabled").invoke(cm, new Object[0]);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return false;
}
/**
* Check if connected to wifi network
*
* @return wifi connected or not
*/
private static boolean isWifiConnected(Context context) {
WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wm != null && wm.isWifiEnabled() && wm.getConnectionInfo().getNetworkId() != -1;
}
/**
* Check if mobile data is on or device is connected to wifi network
*/
public static boolean isConnected(Context context) {
return isMobileDataEnabled(context) || isWifiConnected(context);
}}
调用 NetworkUtils.isConnected() 使用
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check connectivity
boolean isConnected = NetworkUtils.isConnected(this);
}}
推荐阅读
- python - Seaborn散点图增加了vline标记的粗细
- amazon-web-services - AWS 使用 Terraform 导入 vpc
- swiftui - 如果不在 ScrollView 或 List 中,LazyVStack 是否不懒惰?
- javascript - 如果子元素为空,则隐藏 div
- r - 使用 dplyr 编程:间接控制要分组的变量
- python - 如何在 Django Rest Framework 中序列化 ChoiceFields?
- html - HTML 跳转到页面上的另一个位置不起作用
- javascript - JavaScript fetch() 在 API 查询中抛出错误
- flutter - 位置:^3.2.1,无法销毁活动
- angular - 当 FormGroup 出现新错误时,Angular Reactive 表单不更新