【问题标题】:Android check connectivity on low battery (power saver mode)Android 在电池电量不足时检查连接(省电模式)
【发布时间】:2020-03-23 20:56:42
【问题描述】:
我尝试了以下代码来检查连接:
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 的回答中,here 提供了更多信息。
有谁知道开启节电时如何检查连接?!
【问题讨论】:
标签:
android
broadcastreceiver
【解决方案1】:
在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);
}}