Android special test power consumption - using Android code to achieve

Android APP power consumption test code implementation
 

Android APP power consumption test plan:

Use the built-in battery usage statistics function of the Android system to view the battery usage of the application.

Use a third-party battery testing app such as AccuBattery, GSam Battery Monitor, etc.

Use tools for battery drain testing such as Battery Historian, Monsoon Power Monitor, etc.

Android APP power consumption test source code:


The following are some reference source codes, you can modify and optimize according to your needs:

To use the Android battery usage statistics function:
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
int batteryLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
To use a third-party battery test application:
IntentFilter ifilter = new IntentFilter( Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCA LE, -1);
float batteryPct = level / (float)scale;
use the tool for battery consumption test:
private static final String TAG = "BatteryTest";
private static final int TEST_DURATION_SECONDS = 60;
 
private PowerManager.WakeLock mWakeLock;
private BatteryManager mBatteryManager;
private Handler mHandler;
private Runnable mRunnable;
private boolean mTestRunning;
private int mStartLevel;
private int mEndLevel;
private int mBatteryDrain;
 
private void startBatteryTest() {
    mTestRunning = true;
    mStartLevel = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    mWakeLock.acquire();
    mHandler.postDelayed(mRunnable, TEST_DURATION_SECONDS * 1000);
}
 
private void endBatteryTest() {
    mTestRunning = false;
    mEndLevel = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    mBatteryDrain = mStartLevel - mEndLevel;
    mWakeLock.release();
}
 
private void initBatteryTest() {
    mBatteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
    mHandler = new Handler();
    mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    mRunnable = new Runnable() {
        @Override
        public void run() {
            endBatteryTest();
            Log.i(TAG, "Battery drain: " + mBatteryDrain + "%");
        }
    };
}


The above are some simple Android APP power consumption test schemes and source codes, you can modify and improve them according to your needs. At the same time, in order to accurately test the power consumption of the application, it is recommended to close other applications and services during the test to ensure the accuracy of the test results.

An example of obtaining various status information of the Android battery
The following is an example code for obtaining various status information of the Android battery:

public class BatteryInfoActivity extends AppCompatActivity {
 
    private TextView mBatteryLevelTextView;
    private TextView mBatteryStatusTextView;
    private TextView mBatteryHealthTextView;
    private TextView mBatteryTechnologyTextView;
    private TextView mBatteryTemperatureTextView;
    private TextView mBatteryVoltageTextView;
    private TextView mBatteryPluggedTextView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_battery_info);
 
        mBatteryLevelTextView = findViewById(R.id.battery_level_text_view);
        mBatteryStatusTextView = findViewById(R.id.battery_status_text_view);
        mBatteryHealthTextView = findViewById(R.id.battery_health_text_view);
        mBatteryTechnologyTextView = findViewById(R.id.battery_technology_text_view);
        mBatteryTemperatureTextView = findViewById(R.id.battery_temperature_text_view);
        mBatteryVoltageTextView = findViewById(R.id.battery_voltage_text_view);
        mBatteryPluggedTextView = findViewById(R.id.battery_plugged_text_view);
 
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatusIntent = registerReceiver(null, intentFilter);
        if (batteryStatusIntent != null) {
            int level = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            float batteryLevel = level / (float) scale * 100;
            mBatteryLevelTextView.setText(getString(R.string.battery_level, batteryLevel));
 
            int status = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            String statusString = "";
            switch (status) {
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    statusString = "Charging";
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    statusString = "Discharging";
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    statusString = "Full";
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    statusString = "Not charging";
                    break;
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    statusString = "Unknown";
                    break;
            }
            mBatteryStatusTextView.setText(getString(R.string.battery_status, statusString));
 
            int health = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
            String healthString = "";
            switch (health) {
                case BatteryManager.BATTERY_HEALTH_COLD:
                    healthString = "Cold";
                    break;
                case BatteryManager.BATTERY_HEALTH_DEAD:
                    healthString = "Dead";
                    break;
                case BatteryManager.BATTERY_HEALTH_GOOD:
                    healthString = "Good";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                    healthString = "Overheat";
                    break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                    healthString = "Over voltage";
                    break;
                case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                    healthString = "Unknown";
                    break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                    healthString = "Unspecified failure";
                    break;
            }
            mBatteryHealthTextView.setText(getString(R.string.battery_health, healthString));
 
            String technology = batteryStatusIntent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
            mBatteryTechnologyTextView.setText(getString(R.string.battery_technology, technology));
 
            int temperature = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
            float temperatureCelsius = temperature / 10f;
            mBatteryTemperatureTextView.setText(getString(R.string.battery_temperature, temperatureCelsius));
 
            int voltage = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
            mBatteryVoltageTextView.setText(getString(R.string.battery_voltage, voltage));
 
            int plugged = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            String pluggedString = "";
            switch (plugged) {
                case BatteryManager.BATTERY_PLUGGED_AC:
                    pluggedString = "AC";
                    break;
                case BatteryManager.BATTERY_PLUGGED_USB:
                    pluggedString = "USB";
                    break;
                case BatteryManager.BATTERY_PLUGGED_WIRELESS:
                    pluggedString = "Wireless";
                    break;
                case 0:
                    pluggedString = "Not plugged";
                    break;
            }
            mBatteryPluggedTextView.setText(getString(R.string.battery_plugged, pluggedString));
        }
    }
}
In the above code, we obtained various status information of the battery through the constants and methods of the BatteryManager class, such as battery power, battery status, battery health status, battery technology, battery temperature, battery voltage, and battery charging status. At the same time, we also display these status information on the interface through the TextView control.

Note that getting the battery status information needs to listen to the Intent.ACTION_BATTERY_CHANGED broadcast, so we register this broadcast in the onCreate() method. In addition, when obtaining the battery power, we need to obtain the current power and the maximum power first, and then calculate the percentage of the battery power.

Example of counting Android APP power consumption (mah)
To count the power consumption of Android APP, you can use the methods provided by the BatteryManager class to obtain power information, and record the power information when the APP starts and closes. Then calculate the power difference when the APP is closed to get the power consumption of the APP.

Here is an example of a simple implementation:

public class MainActivity extends AppCompatActivity {     private BatteryManager mBatteryManager;     private int mStartBatteryLevel;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main );         // Get the BatteryManager instance         mBatteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);         // Record the battery power when the APP starts         mStartBatteryLevel = getBatteryLevel();     }     @Override     protected void onDestroy() {         super.onDestroy();         // Calculate the power consumption of the APP
 


 




 


 



 



 

        int endBatteryLevel = getBatteryLevel();
        int batteryConsumed = mStartBatteryLevel - endBatteryLevel;
 
        Log.d("Battery", "APP consumed " + batteryConsumed + " mAh");
    }
 
    /**
     * 获取当前电量
     */
    private int getBatteryLevel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            return (int) (level / (float) scale * 100);
        }
    }
}
in onCreate The () method records the battery power when the APP is started, and the onDestroy() method calculates the power consumption of the APP. The getBatteryLevel() method is used to obtain the current battery level. Depending on the Android version, different methods are used to obtain the battery level information.

The approximate power consumption of the APP, because the battery power may change due to the impact of other applications or system services during the running of the APP.

Guess you like

Origin blog.csdn.net/qq_24373725/article/details/129417558