首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在为android手机充电时检测当前的电流

在为android手机充电时检测当前的电流
EN

Stack Overflow用户
提问于 2014-03-02 17:59:36
回答 1查看 241关注 0票数 0

我想开发一个小的应用程序,显示当前正在由手机在充电期间的电流。这款手机是通过A/C插上的,正在拔1A。

根据我的研究,现有的API如下:

http://developer.android.com/reference/android/os/BatteryManager.html http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

然而,这些只会告诉你,它是通过USB或A/C充电,它的现状。

我想做一些测试,看看不同电缆和A/C适配器的收费率。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-02 18:19:49

您可以使用以下方法检查电池的电平

代码语言:javascript
复制
    private static int checkBatteryLevel(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);

        // Are we charging / charged?
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;

        // If the device is charging then set the state as charging and return.
        if (isCharging)
            return 100;

        // Get the battery level.
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

        // To get the battery level in %
        int batteryLevel = (level * 100) / scale;
        Log.e(Constants.TAG, "Battery Level: " + batteryLevel);

        return batteryLevel;
    }

您可以使用以下接收器检测连接和断开连接

代码语言:javascript
复制
public class BatteryInformationReceiver extends BroadcastReceiver {

    private static final String ACTION_POWER_CONNECTED = "android.intent.action.ACTION_POWER_CONNECTED";
    private static final String ACTION_POWER_DISCONNECTED = "android.intent.action.ACTION_POWER_DISCONNECTED";

    @Override
    public void onReceive(Context context, Intent intent) {

        String intentAction = intent.getAction();
        if (intentAction.equalsIgnoreCase(ACTION_POWER_CONNECTED)) {

        } else if (intentAction.equalsIgnoreCase(ACTION_POWER_DISCONNECTED)) {

        } 

    }
}

并在清单中

代码语言:javascript
复制
<receiver android:name="your.package.receivers.BatteryInformationReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>

,然后,在连接时,使用上述方法计算电池电平。断开连接后,计算出电池的电平。并从电池的时间和价值之间的差异。你可以计算你想要的任何东西。

希望这能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22131190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档