Get battery level only once using Android SDK [duplicate]

試著忘記壹切 提交于 2019-12-17 22:22:29

问题


I've searched on the web and couldn't find the answer to my question. My problem is to get the battery level information only once, eg. calling the function getBatteryLevel(). There are only solutions which are implemented using BroadcastReceiver, but as I know it will be called every time on battery level's change event. Please, tell me how can I get that information only once?


回答1:


The Intent.ACTION_BATTERY_CHANGED broadcast is what's known as a "sticky broadcast." Because this is sticky, you can register for the broadcast with a null receiver which will only get the battery level one time when you call registerReceiver.

A function to get the battery level without receiving updates would look something like this:

public float getBatteryLevel() {
    Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    // Error checking that probably isn't needed but I added just in case.
    if(level == -1 || scale == -1) {
        return 50.0f;
    }

    return ((float)level / (float)scale) * 100.0f; 
}

More data can be pulled from this sticky broadcast. Using the returned batteryIntent you can access other extras as outlined in the BatteryManager class.



来源:https://stackoverflow.com/questions/15746709/get-battery-level-only-once-using-android-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!