获取电池电量只有一次采用了Android SDK [英] Get battery level only once using Android SDK

查看:141
本文介绍了获取电池电量只有一次采用了Android SDK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索,并不能找到答案,我的问题。我的问题是只得到一次电池电量信息,例如。调用函数 getBatteryLevel()。只有其中使用的BroadcastReceiver 实施的解决方案,但我知道它会被要求电池电量的变化的事件每次。请告诉我,我怎样才能得到一次这些信息?

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?

推荐答案

的<一个href="http://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED"><$c$c>Intent.ACTION_BATTERY_CHANGED广播是什么所谓的持久广播。因为这是粘性的,你可以注册为一个空接收广播将只能得到电池电量一个当你调用时间 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; 
}

更多的数据可以从这个持久广播拉。使用返回 batteryIntent 可以作为<一个概述访问其他演员href="http://developer.android.com/reference/android/os/BatteryManager.html"><$c$c>BatteryManager类。

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

这篇关于获取电池电量只有一次采用了Android SDK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆