服务检查电池百分比Android

时间:2016-11-24 09:15:11

标签: android service

我想检查电池百分比,我创建了一项服务,但我如何确定电池百分比是多少,并在达到20%时采取措施?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

试试这个:

private void batteryLevel() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            int rawlevel = intent.getIntExtra("level", -1);
            int scale = intent.getIntExtra("scale", -1);
            int level = -1;
            if (rawlevel >= 0 && scale > 0) {
                level = (rawlevel * 100) / scale;
            }
            mBtn.setText("Battery Level Remaining: " + level + "%");
        }
    };
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}