簡體   English   中英

Android 在電池電量不足時檢查連接性(省電模式)

[英]Android check connectivity on low battery (power saver mode)

我嘗試了下面的代碼來檢查連接:

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);
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM