最近在开发一个与GPS相关的项目,因为其中涉及到了GPS的使用,众所周知,GPS是相当耗电的,因此就想着怎么能知道当前的电量,并且在电量达到一个下限的时候,及时提醒给用户,以根据情况关闭GPS,节省电量,以备电话急用,后来查资料,看API,终于找到了方法,怎么来监视电量,根据电量的变化来获取当前的电量多少,并且根据其它状态综合对手机进行管理,以达到管理最优的状态。
下面是代码:
privateBroadcastReceiver mBatInfoReceiver=newBroadcastReceiver() {
intintLevel=0;
intintScale=0;
publicvoidonReceive(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)) {
caseBatteryManager.BATTERY_STATUS_CHARGING:
BatteryStatus="充电状态";
break;
caseBatteryManager.BATTERY_STATUS_DISCHARGING:
BatteryStatus="放电状态";
break;
caseBatteryManager.BATTERY_STATUS_NOT_CHARGING:
BatteryStatus="未充电";
break;
caseBatteryManager.BATTERY_STATUS_FULL:
BatteryStatus="充满电";
break;
caseBatteryManager.BATTERY_STATUS_UNKNOWN:
BatteryStatus="未知道状态";
break;
}
switch(intent.getIntExtra("plugged",
BatteryManager.BATTERY_PLUGGED_AC)) {
caseBatteryManager.BATTERY_PLUGGED_AC:
BatteryStatus2="AC充电";
break;
caseBatteryManager.BATTERY_PLUGGED_USB:
BatteryStatus2="USB充电";
break;
}
switch(intent.getIntExtra("health",
BatteryManager.BATTERY_HEALTH_UNKNOWN)) {
caseBatteryManager.BATTERY_HEALTH_UNKNOWN:
BatteryTemp="未知错误";
break;
caseBatteryManager.BATTERY_HEALTH_GOOD:
BatteryTemp="状态良好";
break;
caseBatteryManager.BATTERY_HEALTH_DEAD:
BatteryTemp="电池没有电";
break;
caseBatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
BatteryTemp="电池电压过高";
break;
caseBatteryManager.BATTERY_HEALTH_OVERHEAT:
BatteryTemp="电池过热";
break;
}
}
}
};
这些信息就是监听广播,根据广播的信息进行判断,如果是电量变化的广播,那么就根据这些信息,更新数据,从而进行分析!