Android 對電池狀態的監視

來源:互聯網
上載者:User

    最近在開發一個與GPS相關的項目,因為其中涉及到了GPS的使用,眾所周知,GPS是相當耗電的,因此就想著怎麼能知道當前的電量,並且在電量達到一個下限的時候,及時提醒給使用者,以根據情況關閉GPS,節省電量,以備電話急用,後來查資料,看API,終於找到了方法,怎麼來監視電量,根據電量的變化來擷取當前的電量多少,並且根據其它狀態綜合對手機進行管理,以達到管理最優的狀態。

    下面是代碼:

代碼

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
int intLevel = 0;
int intScale = 0;

public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/*
* 如果捕捉到的action是ACTION_BATTERY_CHANGED, 就運行onBatteryInfoReceiver()
*/
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
intLevel = intent.getIntExtra("level", 0);
intScale = intent.getIntExtra("scale", 100);

// 電池伏數
Log.d("Battery V", "" + intent.getIntExtra("voltage", 0));
// 電池溫度
Log.d("Battery T", "" + intent.getIntExtra("temperature", 0));
BatteryV = "當前電壓為:" + intent.getIntExtra("voltage", 0);
BatteryT = "當前溫度為:" + intent.getIntExtra("temperature", 0);

switch (intent.getIntExtra("status",
BatteryManager.BATTERY_STATUS_UNKNOWN)) {
case BatteryManager.BATTERY_STATUS_CHARGING:
BatteryStatus = "充電狀態";
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
BatteryStatus = "放電狀態";
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
BatteryStatus = "未充電";
break;
case BatteryManager.BATTERY_STATUS_FULL:
BatteryStatus = "充滿電";
break;
case BatteryManager.BATTERY_STATUS_UNKNOWN:
BatteryStatus = "未知道狀態";
break;
}
switch (intent.getIntExtra("plugged",
BatteryManager.BATTERY_PLUGGED_AC)) {
case BatteryManager.BATTERY_PLUGGED_AC:
BatteryStatus2 = "AC充電";
break;
case BatteryManager.BATTERY_PLUGGED_USB:
BatteryStatus2 = "USB充電";
break;
}

switch (intent.getIntExtra("health",
BatteryManager.BATTERY_HEALTH_UNKNOWN)) {
case BatteryManager.BATTERY_HEALTH_UNKNOWN:
BatteryTemp = "未知錯誤";
break;
case BatteryManager.BATTERY_HEALTH_GOOD:
BatteryTemp = "狀態良好";
break;
case BatteryManager.BATTERY_HEALTH_DEAD:
BatteryTemp = "電池沒有電";
break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
BatteryTemp = "電池電壓過高";
break;
case BatteryManager.BATTERY_HEALTH_OVERHEAT:
BatteryTemp = "電池過熱";
break;
}

}
}

};

 

這些資訊就是監聽廣播,根據廣播的資訊進行判斷,如果是電量變化的廣播,那麼就根據這些資訊,更新資料,從而進行分析!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.