当前位置: 网学 > 编程文档 > Android > 正文

Android中电池信息(Battery information)的取得

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: myeducs.cn 发布时间: 13/03/17

【网学网提醒】:网学会员为您提供Android中电池信息(Battery information)的取得参考,解决您在Android中电池信息(Battery information)的取得学习中工作中的难题,参考学习


    Android中电池信息(Batteryinformation)的取得
    [日期:2010-08-23] 来源:Linux社区作者:Linux
    这里介绍电池信息的取得.
    Android.content.BroadcastReceiver类
    Android.os.BatteryManager类
    ●电池信息的取得,调用registerReceiver()方法。
    第1个参数,设置BroadcastReceiver实例
    第2个参数,设置追加了Intent.ACTION_BATTERY_CHANGED处理的IntentFilter实例。
    ●在BroadcastReceiver的onReceive()事件,接收到的Intent.ACTION_BATTERY_CHANGED,包括下面的信息。
    “status”(int类型)…状态,定义值是BatteryManager.BATTERY_STATUS_XXX。
    “health”(int类型)…健康,定义值是BatteryManager.BATTERY_HEALTH_XXX。
    “present”(boolean类型)
    “level”(int类型)…电池剩余容量
    “scale”(int类型)…电池最大值。通常为100。
    “icon-small”(int类型)…图标ID。
    “plugged”(int类型)…连接的电源插座,定义值是BatteryManager.BATTERY_PLUGGED_XXX。
    “voltage”(int类型)…mV。
    “temperature”(int类型)…温度,0.1度单位。例如表示197的时候,意思为19.7度。
    “technology”(String类型)…电池类型,例如,Li-ion等等。
    例程源码(Java)
    packagecom.adakoda.batterytest;
    importAndroid.app.Activity;
    importAndroid.content.BroadcastReceiver;
    importAndroid.content.Context;
    importAndroid.content.Intent;
    importAndroid.content.IntentFilter;
    importAndroid.os.BatteryManager;
    importAndroid.os.Bundle;
    importAndroid.util.Log;
    publicclassBatteryTestActivityextendsActivity{
    /**Calledwhentheactivityisfirstcreated.*/
    @Override
    publicvoidonCreate(BundlesavedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }
    @Override
    protectedvoidonResume(){
    super.onResume();
    
    IntentFilterfilter=newIntentFilter();
    
    filter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(mBroadcastReceiver,filter);
    }
    @Override
    protectedvoidonPause(){
    super.onPause();
    
    unregisterReceiver(mBroadcastReceiver);
    }
    privateBroadcastReceivermBroadcastReceiver=newBroadcastReceiver(){
    @Override
    publicvoidonReceive(Contextcontext,Intentintent){
    Stringaction=intent.getAction();
    if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
    intstatus=intent.getIntExtra("status",0);
    inthealth=intent.getIntExtra("health",0);
    booleanpresent=intent.getBooleanExtra("present",false);
    intlevel=intent.getIntExtra("level",0);
    intscale=intent.getIntExtra("scale",0);
    inticon_small=intent.getIntExtra("icon-small",0);
    intplugged=intent.getIntExtra("plugged",0);
    intvoltage=intent.getIntExtra("voltage",0);
    inttemperature=intent.getIntExtra("temperature",0);
    Stringtechnology
    =intent.getStringExtra("technology");
    
    StringstatusString="";
    
    switch(status){
    caseBatteryManager.BATTERY_STATUS_UNKNOWN:
    statusString="unknown";
    break;
    caseBatteryManager.BATTERY_STATUS_CHARGING:
    statusString="charging";
    break;
    caseBatteryManager.BATTERY_STATUS_DISCHARGING:
    statusString="discharging";
    break;
    caseBatteryManager.BATTERY_STATUS_NOT_CHARGING:
    statusString="notcharging";
    break;
    caseBatteryManager.BATTERY_STATUS_FULL:
    statusString="full";
    break;
    }
    
    StringhealthString="";
    
    switch(health){
    caseBatteryManager.BATTERY_HEALTH_UNKNOWN:
    healthString="unknown";
    break;
    caseBatteryManager.BATTERY_HEALTH_GOOD:
    healthString="good";
    break;
    caseBatteryManager.BATTERY_HEALTH_OVERHEAT:
    healthString="overheat";
    break;
    caseBatteryManager.BATTERY_HEALTH_DEAD:
    healthString="dead";
    break;
    caseBatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
    healthString="voltage";
    break;
    caseBatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
    healthString="unspecifiedfailure";
    break;
    }
    
    StringacString="";
    
    switch(plugged){
    caseBatteryManager.BATTERY_PLUGGED_AC:
    acString="pluggedac";
    break;
    caseBatteryManager.BATTERY_PLUGGED_USB:
    acString="pluggedusb";
    break;
    }
    
    Log.v("status",statusString);
    Log.v("health",healthString);
    Log.v("present",String.valueOf(present));
    Log.v("level",String.valueOf(level));
    Log.v("scale",String.valueOf(scale));
    Log.v("icon_small",String.valueOf(icon_small));
    Log.v("plugged",acString);
    Log.v("voltage",String.valueOf(voltage));
    Log.v("temperature",String.valueOf(temperature));
    Log.v("technology",technology);
    }
    }
    };
    Android中电池信息(Batteryinformation)的取得收藏
    原文地址:blog.csdn.net/sharp2wing/archive/2010/08/20/5826493.aspx
    这里介绍电池信息的取得.
    android.content.BroadcastReceiver类
    android.os.BatteryManager类
    ●电池信息的取得,调用registerReceiver()方法。
    第1个参数,设置BroadcastReceiver实例
    第2个参数,设置追加了Intent.ACTION_BATTERY_CHANGED处理的IntentFilter实例。
    ●在BroadcastReceiver的onReceive()事件,接收到的Intent.ACTION_BATTERY_CHANGED,包括下面的信息。
    “status”(int类型)…状态,定义值是BatteryManager.BATTERY_STATUS_XXX。
    “health”(int类型)…健康,定义值是BatteryManager.BATTERY_HEALTH_XXX。
    “present”(boolean类型)
    
    “level”(int类型)…电池剩余容量
    “scale”(int类型)…电池最大值。通常为100。
    “icon-small”(int类型)…图标ID。
    “plugged”(int类型)…连接的电源插座,定义值是BatteryManager.BATTERY_PLUGGED_XXX。
    “voltage”(int类型)…mV。
    “temperature”(int类型)…温度,0.1度单位。例如表示197的时候,意思为19.7度。
    “technology”(String类型)…电池类型,例如,Li-ion等等。
    }
    原创Android中的BatteryService及相关组件收藏
    转载时请注明出处和作者联系方式
    文章出处:limodev/blog
    作者联系方式:李先静
    BatteryService作为电池及充电相关的服务,它的实现非常简单:
    o监听UEvent,读取sysfs里中的状态。
    实现了一个UEvent的观察者。uevent是Linux内核用来向用户空间主动上报事件的机制,对于JAVA程序来说,只实现UEventObserver的虚函数onUEvent,然后注册即可。
    privateUEventObservermUEventObserver=newUEventObserver(){
    @Override
    publicvoidonUEvent(UEventObserver.UEventevent){
    update();
    }
    };
    这里只关注power_supply的事件:
    mUEventObserver.startObserving("SUBSYSTEM=power_supply");
    当有power_supply相关的事件上报时,就会调用update函数。
    update先调用native_update从sysfs中读取相关状态(com_android_server_BatteryService.cpp):
    Linux驱动提供了下列文件,供应用程序获取电源相关状态:
    #defineAC_ONLINE_PATH"/sys/class/power_supply/ac/online"
    #defineUSB_ONLINE_PATH"/sys/class/power_supply/usb/online"
    #defineBATTERY_STATUS_PATH"/sys/class/power_supply/battery/status"
    #defineBATTERY_HEALTH_PATH"/sys/class/power_supply/battery/health"
    #defineBATTERY_PRESENT_PATH"/sys/class/power_supply/battery/present"
    #defineBATTERY_CAPACITY_PATH"/sys/class/power_supply/battery/capacity"
    #defineBATTERY_VOLTAGE_PATH"/sys/class/power_supply/battery/batt_vol"
    #defineBATTERY_TEMPERATURE_PATH"/sys/class/power_supply/battery/batt_temp"
    #defineBATTERY_TECHNOLOGY_PATH"/sys/class/power_supply/battery/technology"
    在<DA9034驱动程序阅读笔记(6)>一文中,我已经提到drivers/power/micco_power.c里注册了充电器(ac)、usb和电池(battery)三个power_supply。各个power_supply提供的属性和上述文件是对应的,从这些文件中可以读到充电器(ac)、usb和电池(battery)三个power_supply的相应状态。
    update然后根据读到的状态更新BatteryService的成员变量,并广播一个Intent来通知其它关注电源状态的组件。
    privatefinalvoidsendIntent(){
    //Packupthevaluesandbroadcastthemtoeveryone
    Intentintent=newIntent(Intent.ACTION_BATTERY_CHANGED);
    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    try{
    mBatteryStats.setOnBattery(mPlugType
    ==BATTERY_PLUGGED_NONE,mBatteryLevel);
    }catch(RemoteExceptione){
    //Shouldneverhappen.
    }
    
    inticon=getIcon(mBatteryLevel);
    
    intent.putExtra("status",mBatteryStatus);
    intent.putExtra("health",mBatteryHealth);
    intent.putExtra("present",mBatteryPresent);
    intent.putExtra("level",mBatteryLevel);
    intent.putExtra("scale",BATTERY_SCALE);
    intent.putExtra("icon-small",icon);
    intent.putExtra("plugged",mPlugType);
    intent.putExtra("voltage",mBatteryVoltage);
    intent.putExtra("temperature",mBatteryTemperature);
    intent.putExtra("technology",mBatteryTechnology);
    
    ActivityManagerNative.broadcastStickyIntent(intent,null);
    }
    关注ACTION_BATTERY_CHANGED的地方有好几个:
    oKeyguardUpdateMonitor这里主要是用来更新锁屏界面下的电池状态。还有低电警告和关机也是在这里做的。
    privatevoidhandleBatteryUpdate(intpluggedInStatus,intbatteryLevel){
    if(DEBUG)Log.d(TAG,"handleBatteryUpdate");
    finalbooleanpluggedIn=isPluggedIn(pluggedInStatus);
    
    if(isBatteryUpdateInteresting(pluggedIn,batteryLevel)){
    mBatteryLevel=batteryLevel;
    mDevicePluggedIn=pluggedIn;
    for(inti=0;i    mInfoCallbacks.get(i).onRefreshBatteryInfo(
    shouldShowBatteryInfo(),pluggedIn,batteryLevel);
    }
    }
    
    //shutdowngracefullyifourbatteryiscriticallylowandwearenotpowered
    if(batteryLevel==0&;&;
    pluggedInStatus!=BATTERY_STATUS_CHARGING&;&;
    pluggedInStatus!=BATTERY_STATUS_UNKNOWN){
    
    ShutdownThread.shutdownAfterDisablingRadio(mContext,false);
    
    }
    }
    oNotificationManagerService用来更新充电状态(LED)
    if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
    booleanbatteryCharging=(intent.getIntExtra("plugged",0)!=0);
    intlevel=intent.getIntExtra("level",-1);
    booleanbatteryLow=(level>=0&;&;level<=Power.LOW_BATTERY_THRESHOLD);
    intstatus=intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN);
    booleanbatteryFull=(status==BatteryManager.BATTERY_STATUS_FULL||level>=90);
    
    if(batteryCharging!=mBatteryCharging||
    batteryLow!=mBatteryLow||
    batteryFull!=mBatteryFull){
    mBatteryCharging=batteryCharging;
    mBatteryLow=batteryLow;
    mBatteryFull=batteryFull;
    updateLights();
    }
    }
    oPowerManagerService这里主要是做两件事件,先是检查是否在充电时不允许睡眠,并采用相应的行动,其次是触发一个用户行为(会影响下一次
    睡眠的时间)。
    privatefinalclassBatteryReceiverextendsBroadcastReceiver{
    @Override
    publicvoidonReceive(Contextcontext,Intentintent){
    synchronized(mLocks){
    booleanwasPowered=mIsPowered;
    mIsPowered=mBatteryService.isPowered();
    
    if(mIsPowered!=wasPowered){
    //updatemStayOnWhilePluggedInwakelock
    updateWakeLockLocked();
    
    //treatpluggingandunpluggingthedevicesasauseractivity.
    //usersfinditdisconcertingwhentheyunplugthedevice
    //anditshutsoffrightaway.
    //temporarilysetmUserActivityAllowedtotruesothiswillwork
    //evenwhenthekeyguardison.
    synchronized(mLocks){
    booleansavedActivityAllowed=mUserActivityAllowed;
    mUserActivityAllowed=true;
    userActivity(SystemClock.uptimeMillis(),false);
    mUserActivityAllowed=savedActivityAllowed;
    }
    }
    }
    }
    }
    oLocationManagerService这里似乎没有什么用处,我没找到mCollector赋值的地方。
    if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
    log("PowerStateBroadcastReceiver:Batterychanged");
    synchronized(mLocationListeners){
    intscale=intent.getIntExtra(BATTERY_EXTRA_SCALE,100);
    intlevel=intent.getIntExtra(BATTERY_EXTRA_LEVEL,0);
    booleanplugged=intent.getIntExtra(BATTERY_EXTRA_PLUGGED,0)!=0;
    
    //Notifycollectorbatterystate
    if(mCollector!=null){
    mCollector.updateBatteryState(scale,level,plugged);
    }
    }
    }
    oWifiService根据电源状态来决定是否需要定时唤醒(没搞得太明白,看Wifi服务时再研究)。
    if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
    /*
    *SetatimertoputWi-Fitosleep,butonlyifthescreenisoff
    *ANDwearetransitioningfromastateinwhichthedevicewassupposed
    *tostayawaketoastateinwhichitisnotsupposedtostayawake.
    *If"stayawake"stateisnotchanging,wedonothing,toavoidresetting
    *thealready-settimer.
    */
    intpluggedType=intent.getIntExtra("plugged",0);
    if(mScreenOff&;&;shouldWifiStayAwake(stayAwakeConditions,mPluggedType)&;&;
    !shouldWifiStayAwake(stayAwakeConditions,pluggedType)){
    longtriggerTime=System.currentTimeMillis()+idleMillis;
    mAlarmManager.set(AlarmManager.RTC_WAKEUP,triggerTime,mIdleIntent);
    
    mPluggedType=pluggedType;
    return;
    }
    mPluggedType=pluggedType;
    }
    oStatusBarPolicy用来更新状态栏上的充电图标。
    if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
    updateBattery(intent);
    }
    Android手机电池信息
    Android开发技术2009-08-0912:22:25阅读580评论0字号:大中小订阅
    以下是手机电池的一些信息,很有用的。可以获得手机的好多参数。如电压,手机电量的多少,等等。
    packagecom.android.settings;
    19importandroid.app.Activity;
    20importandroid.content.BroadcastReceiver;
    21importandroid.content.Context;
    22importandroid.content.Intent;
    23importandroid.content.IntentFilter;
    24importandroid.os.BatteryManager;
    25importandroid.os.Bundle;
    26importandroid.os.Handler;
    27importandroid.os.IPowerManager;
    28importandroid.os.Message;
    29importandroid.os.RemoteException;
    30importandroid.os.ServiceManager;
    31importandroid.os.SystemClock;
    32importandroid.text.format.DateUtils;
    33importandroid.widget.TextView;
    34
    35importcom.android.internal.app.IBatteryStats;
    36
    37publicclassBatteryInfoextendsActivity{
    38privateTextViewmStatus;
    39privateTextViewmLevel;
    40privateTextViewmScale;
    41privateTextViewmHealth;
    42privateTextViewmVoltage;
    43privateTextViewmTemperature;
    44privateTextViewmTechnology;
    45privateTextViewmUptime;
    46privateIBatteryStatsmBatteryStats;
    47privateIPowerManagermScreenStats;
    48
    49privatestaticfinalintEVENT_TICK=1;
    50
    51privateHandlermHandler=newHandler(){
    52@Override
    53publicvoidhandleMessage(Messagemsg){
    54switch(msg.what){
    55caseEVENT_TICK:
    56updateBatteryStats();
    57sendEmptyMessageDelayed(EVENT_TICK,1000);
    58
    59break;
    60}
    61}
    62};
    63
    64/**
    65*Formatanumberoftenths-unitsasadecimalstringwithoutusinga
    66*conversiontofloat.E.g.347->"34.7"
    67*/
    68privatefinalStringtenthsToFixedString(intx){
    69inttens=x/10;
    70returnnewString(""+tens+"."+(x-10*tens));
    71}
    72
    73/**
    74*Listensforintentbroadcasts
    75*/
    76privateIntentFiltermIntentFilter;
    77
    78privateBroadcastReceivermIntentReceiver=newBroadcastReceiver(){
    79@Override
    80publicvoidonReceive(Contextcontext,Intentintent){
    81Stringaction=intent.getAction();
    82if(action.equals(Intent.ACTION_BATTERY_CHANGED)){
    83intplugType=intent.get
    IntExtra("plugged",0);
    84
    85mLevel.setText(""+intent.getIntExtra("level",0));
    86mScale.setText(""+intent.getIntExtra("scale",0));
    87mVoltage.setText(""+intent.getIntExtra("voltage",0)+""
    88+getString(R.string.battery_info_voltage_units));
    89mTemperature.setText(""+tenthsToFixedString(intent.getIntExtra("temperature",0))
    90+getString(R.string.battery_info_temperature_units));
    91mTechnology.setText(""+intent.getStringExtra("technology"));
    92
    93intstatus=intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN);
    94StringstatusString;
    95if(status==BatteryManager.BATTERY_STATUS_CHARGING){
    96statusString=getString(R.string.battery_info_status_charging);
    97if(plugType>0){
    98statusString=statusString+""+getString(
    99(plugType==BatteryManager.BATTERY_PLUGGED_AC)
    100?R.string.battery_info_status_charging_ac
    101:R.string.battery_info_status_charging_usb);
    102}
    103}elseif(status==BatteryManager.BATTERY_STATUS_DISCHARGING){
    104statusString=getString(R.string.battery_info_status_discharging);
    105}elseif(status==BatteryManager.BATTERY_STATUS_NOT_CHARGING){
    106statusString=getString(R.string.battery_info_status_not_charging);
    107}elseif(status==BatteryManager.BATTERY_STATUS_FULL){
    108statusString=getString(R.string.battery_info_status_full);
    109}else{
    110statusString=getString(R.string.battery_info_status_unknown);
    111}
    112mStatus.setText(statusString);
    113
    114inthealth=intent.getIntExtra("health",BatteryManager.BATTERY_HEALTH_UNKNOWN);
    115StringhealthString;
    116if(health==BatteryManager.BATTERY_HEALTH_GOOD){
    117healthString=getString(R.string.battery_info_health_good);
    118}elseif(health==BatteryManager.BATTERY_HEALTH_OVERHEAT){
    119healthString=getString(R.string.battery_info_health_overheat);
    120}elseif(health==BatteryManager.BATTERY_HEALTH_DEAD){
    121healthString=getString(R.string.battery_info_health_dead);
    122}elseif(health==BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
    123healthString=getString(R.string.battery_info_health_over_voltage);
    124}elseif(health==Batter
    yManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
    125healthString=getString(R.string.battery_info_health_unspecified_failure);
    126}else{
    127healthString=getString(R.string.battery_info_health_unknown);
    128}
    129mHealth.setText(healthString);
    130}
    131}
    132};
    133
    134@Override
    135publicvoidonCreate(Bundleicicle){
    136super.onCreate(icicle);
    137
    138setContentView(R.layout.battery_info);
    139
    140//createtheIntentFilterthatwillbeusedtolisten
    141//tobatterystatusbroadcasts
    142mIntentFilter=newIntentFilter();
    143mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    144}
    145
    146@Override
    147publicvoidonResume(){
    148super.onResume();
    149
    150mStatus=(TextView)findViewById(R.id.status);
    151mLevel=(TextView)findViewById(R.id.level);
    152mScale=(TextView)findViewById(R.id.scale);
    153mHealth=(TextView)findViewById(R.id.health);
    154mTechnology=(TextView)findViewById(R.id.technology);
    155mVoltage=(TextView)findViewById(R.id.voltage);
    156mTemperature=(TextView)findViewById(R.id.temperature);
    157mUptime=(TextView)findViewById(R.id.uptime);
    158
    159//Getawaketimepluggedinandonbattery
    160mBatteryStats=IBatteryStats.Stub.asInterface(ServiceManager.getService("batteryinfo"));
    161mScreenStats=IPowerManager.Stub.asInterface(ServiceManager.getService(POWER_SERVICE));
    162mHandler.sendEmptyMessageDelayed(EVENT_TICK,1000);
    163
    164registerReceiver(mIntentReceiver,mIntentFilter);
    165}
    166
    167@Override
    168publicvoidonPause(){
    169super.onPause();
    170mHandler.removeMessages(EVENT_TICK);
    171
    172//wearenolongeronthescreenstoptheobservers
    173unregisterReceiver(mIntentReceiver);
    174}
    175
    176privatevoidupdateBatteryStats(){
    177longuptime=SystemClock.elapsedRealtime();
    178mUptime.setText(DateUtils.formatElapsedTime(uptime/1000));
    179
    180}
    181
    182}
    
  • 上一篇资讯: android中的数据库操作
  • 网学推荐

    免费论文

    原创论文

    浏览:
    设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
    版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
    Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
    湘ICP备09003080号