Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> Android 對電池狀態的監視

Android 對電池狀態的監視

編輯:Android開發實例

    最近在開發一個與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;
}

}
}

};

 

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

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved