1. 程式人生 > >Android之檢視手機實時電流、電壓

Android之檢視手機實時電流、電壓

就是從檔案中讀值,由於電流變化太快,顯示的是連續讀5次的平均值,直接上程式碼:

public class MainActivity extends Activity {

    private boolean mIsStart = true;
    private Toast mToast;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            showToast(getCurrent());
            if (mIsStart) {
                // 因為Toast.LENGTH_SHORT的預設值是2000
                mHandler.sendEmptyMessageDelayed(0, 1900);
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler.sendEmptyMessage(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(0);
        mIsStart = false;
    }

    /**
     * 獲取當前電流
     */
    private String getCurrent() {
        String result = "null";
        try {
            Class systemProperties = Class.forName("android.os.SystemProperties");
            Method get = systemProperties.getDeclaredMethod("get", String.class);
            String platName = (String) get.invoke(null, "ro.hardware");
            if (platName.startsWith("mt") || platName.startsWith("MT")) {
                String filePath = "/sys/class/power_supply/battery/device/FG_Battery_CurrentConsumption";
                // MTK平臺該值不區分充放電,都為負數,要想實現充放電電流增加廣播監聽充電狀態即可
                result = "當前電流為:" + Math.round(getMeanCurrentVal(filePath, 5, 0) / 10.0f) + "mA";
                result += ", 電壓為:" + readFile("/sys/class/power_supply/battery/batt_vol", 0) + "mV";
            } else if (platName.startsWith("qcom")) {
                String filePath ="/sys/class/power_supply/battery/current_now";
                int current = Math.round(getMeanCurrentVal(filePath, 5, 0) / 10.0f);
                int voltage = readFile("/sys/class/power_supply/battery/voltage_now", 0) / 1000;
                // 高通平臺該值小於0時電池處於放電狀態,大於0時處於充電狀態
                if (current < 0) {
                    result = "充電電流為:" + (-current) + "mA, 電壓為:" + voltage + "mV";
                } else {
                    result = "放電電流為:" + current + "mA, 電壓為:" + voltage + "mV";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 獲取平均電流值
     * 獲取 filePath 檔案 totalCount 次數的平均值,每次取樣間隔 intervalMs 時間 
     */
    private float getMeanCurrentVal(String filePath, int totalCount, int intervalMs) {
        float meanVal = 0.0f;
        if (totalCount <= 0) {
            return 0.0f;
        }
        for (int i = 0; i < totalCount; i++) {
            try {
                float f = Float.valueOf(readFile(filePath, 0));
                meanVal += f / totalCount;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (intervalMs <= 0) {
                continue;
            }
            try {
                Thread.sleep(intervalMs);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return meanVal;
    }

    private int readFile(String path, int defaultValue) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(
                    path));
            int i = Integer.parseInt(bufferedReader.readLine(), 10);
            bufferedReader.close();
            return i;
        } catch (Exception localException) {
        }
        return defaultValue;
    }

    private void showToast(String content) {
        if (mToast == null) {
            mToast = Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(content);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

}