简体   繁体   中英

Is there a system variable that holds the device-specific low-battery threshold for Android?

I am checking to see if the battery has reached critical level.

Android sends an intent to your app when the battery crosses the low-battery threshold in either direction. But this only works if the threshold is crossed while your app is running (the intent is not sticky, so it doesn't hang around). So if it's low when the user opens the app, you're out of luck (or at least information).

There is also a sticky intent, ACTION_BATTERY_CHANGED, that has information about the battery level and a scale for calculating percentages, which is great. However, I have been unable to find the system variable that contains the low-battery threshold (it apparently varies across device).

Doing a search, I found: When android fires ACTION_BATTERY_LOW , a source listing of Android system code, which uses the system variable com.android.internal.R.integer.config_lowBatteryWarningLevel. However, I have been unable to access this variable myself (my guess is that it is protected).

I would like to have a reasonable standard to compare my battery percentage to, so I know when to turn off battery-intensive functionality. That is all.

Here is my code:

private BroadcastReceiver powerListener = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
    int batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    int batteryScale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
        int batteryPercentLeft = (batteryLevel * 100) / batteryScale;

        if (batteryPercentLeft <= com.android.internal.R.integer.config_lowBatteryWarningLevel) {
            _thread.onBatteryStateReceived(DataModel.BatteryState.LOW);
        }
    }
};

I get a compile error for the system variable. Is there an alternative? It seems like this should be a straightforward thing to do. I just want to match system behavior, nothing fancy.

Note that this is possible, but uses reflection so should not be relied upon:

    try {
        Class clazz = Class.forName("com.android.internal.R$integer");
        Field field = clazz.getDeclaredField("config_lowBatteryWarningLevel");
        field.setAccessible(true);
        int LowBatteryLevel = _context.getResources().getInteger(field.getInt(null));
        Log.d("LowBattery","warninglevel " + LowBatteryLevel);
    } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }

Source: https://stackoverflow.com/a/49424298/608312

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM