在应用程序启动时获取电池电量

时间:2018-05-07 06:44:21

标签: android batterylevel

在我的应用中,我使用" ACTION_BATTERY_CHANGED" 意图查找Android设备的电池电量。

**问题:**

考虑如果设备的电池电量为1-20,我需要在我的应用程序中显示低电量图标。我无法立即显示

我已经在应用程序启动时注册了 ACTION_BATTERY_CHANGED Intent的广播接收器。由于这是系统范围的公告,我无法立即获得。

我可以在App Launch上使用SendBroadcast()触发 ACTION_BATTERY_CHANGED Intent的广播吗?

这是正确的行为吗?

2 个答案:

答案 0 :(得分:0)

获得电池电量的最佳方法是

           String currentBatteryStatus = "Battery Percentage";
            int deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int batteryLevel = (int) (((float) level / (float) scale) * 100.0f);

            if (deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
                currentBatteryStatus = currentBatteryStatus + " Charging : " + batteryLevel + " %";
            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING) {
                currentBatteryStatus = currentBatteryStatus + " Discharging : " + batteryLevel + " %";
            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL) {
                currentBatteryStatus = currentBatteryStatus + " Battery Full : " + batteryLevel + " %";
            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
                currentBatteryStatus = currentBatteryStatus + " Unknown : " + batteryLevel + " %";
            }

            if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
                currentBatteryStatus = currentBatteryStatus + " Not Charging : " + batteryLevel + " %";
            }

如果您有任何疑问,请问我

答案 1 :(得分:-1)

ACTION_BATTERY_CHANGED是粘性意图,只要您为此广播注册接收器,您应该获得它的最后修改值。 这似乎与您的广播设置有关。你可以这样做:

    BroadcastReceiver powerReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                    Logger.e("Power", "Battrery NOW " + String.valueOf(level) + "%");
                    //Your logic here

                }
            };

            @Override
            public void onResume() {
                super.onResume();
                getBaseActivity().registerReceiver(powerReceiver,
                        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));    
            }

            @Override
            public void onPause() {
                super.onPause();
                getBaseActivity().unregisterReceiver(powerReceiver);
            }