android5.1BatteryService深入分析

先贴一张类与类之间的关系图:

构造函数只是从资源中取一些值。

  1. public BatteryService(Context context) {  
  2.     super(context);  
  3.   
  4.     mContext = context;  
  5.     mHandler = new Handler(true /*async*/);  
  6.     mLed = new Led(context, getLocalService(LightsManager.class));  
  7.     mBatteryStats = BatteryStatsService.getService();  
  8.   
  9.     mCriticalBatteryLevel = mContext.getResources().getInteger(  
  10.             com.android.internal.R.integer.config_criticalBatteryWarningLevel);  
  11.     mLowBatteryWarningLevel = mContext.getResources().getInteger(  
  12.             com.android.internal.R.integer.config_lowBatteryWarningLevel);  
  13.     mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(  
  14.             com.android.internal.R.integer.config_lowBatteryCloseWarningBump);  
  15.     mShutdownBatteryTemperature = mContext.getResources().getInteger(  
  16.             com.android.internal.R.integer.config_shutdownBatteryTemperature);  
  17.   
  18.     // watch for invalid charger messages if the invalid_charger switch exists  
  19.     if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {  
  20.         mInvalidChargerObserver.startObserving(  
  21.                 "DEVPATH=/devices/virtual/switch/invalid_charger");  
  22.     }  
  23. }  

onstart函数将电池监听注册到底层去。

[java] view plain copy

  1. @Override  
  2. public void onStart() {  
  3.     IBinder b = ServiceManager.getService("batteryproperties");  
  4.     final IBatteryPropertiesRegistrar batteryPropertiesRegistrar =  
  5.             IBatteryPropertiesRegistrar.Stub.asInterface(b);  
  6.     try {  
  7.         //电池监听,注册到底层。当底层电量改变会调用此监听。然后执行update  
  8.         batteryPropertiesRegistrar.registerListener(new BatteryListener());  
  9.     } catch (RemoteException e) {  
  10.         // Should never happen.  
  11.     }  
  12.       
  13.     publishBinderService("battery", new BinderService());  
  14.     publishLocalService(BatteryManagerInternal.class, new LocalService());  
  15. }  

将本地接口publish出去。

 

[java] view plain copy

  1. private final class LocalService extends BatteryManagerInternal {  
  2.     @Override  
  3.     public boolean isPowered(int plugTypeSet) {  
  4.         synchronized (mLock) {  
  5.             return isPoweredLocked(plugTypeSet);  
  6.         }  
  7.     }  
  8.   
  9.     @Override  
  10.     public int getPlugType() {  
  11.         synchronized (mLock) {  
  12.             return mPlugType;  
  13.         }  
  14.     }  
  15.   
  16.     @Override  
  17.     public int getBatteryLevel() {  
  18.         synchronized (mLock) {  
  19.             return mBatteryProps.batteryLevel;  
  20.         }  
  21.     }  
  22.   
  23.     @Override  
  24.     public boolean getBatteryLevelLow() {  
  25.         synchronized (mLock) {  
  26.             return mBatteryLevelLow;  
  27.         }  
  28.     }  
  29.   
  30.     @Override  
  31.     public int getInvalidCharger() {  
  32.         synchronized (mLock) {  
  33.             return mInvalidCharger;  
  34.         }  
  35.     }  
  36. }  

 

 

 

当底层有信息上来,会调用update函数更新BatteryService中的状态值。

[java] view plain copy

  1. private void update(BatteryProperties props) {  
  2.     synchronized (mLock) {  
  3.         if (!mUpdatesStopped) {  
  4.             mBatteryProps = props;  
  5.             // Process the new values.  
  6.             processValuesLocked(false);  
  7.         } else {  
  8.             mLastBatteryProps.set(props);  
  9.         }  
  10.     }  
  11. }  

 

接下来分析主函数processValuesLocked:

 

[java] view plain copy

  1. private void processValuesLocked(boolean force) {  
  2.        boolean logOutlier = false;  
  3.        long dischargeDuration = 0;  
  4.   
  5.        mBatteryLevelCritical = (mBatteryProps.batteryLevel <= mCriticalBatteryLevel);  
  6.        //解析充电类型  
  7.        if (mBatteryProps.chargerAcOnline) {  
  8.            mPlugType = BatteryManager.BATTERY_PLUGGED_AC;  
  9.        } else if (mBatteryProps.chargerUsbOnline) {  
  10.            mPlugType = BatteryManager.BATTERY_PLUGGED_USB;  
  11.        } else if (mBatteryProps.chargerWirelessOnline) {  
  12.            mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;  
  13.        } else {  
  14.            mPlugType = BATTERY_PLUGGED_NONE;  
  15.        }  
  16.   
  17.   
  18.        // Let the battery stats keep track of the current level.  
  19.        try {  
  20.            mBatteryStats.setBatteryState(mBatteryProps.batteryStatus, mBatteryProps.batteryHealth,  
  21.                    mPlugType, mBatteryProps.batteryLevel, mBatteryProps.batteryTemperature,  
  22.                    mBatteryProps.batteryVoltage);  
  23.        } catch (RemoteException e) {  
  24.            // Should never happen.  
  25.        }  
  26.        //没电了  
  27.        shutdownIfNoPowerLocked();  
  28.        //温度过高  
  29.        shutdownIfOverTempLocked();  
  30.        //force用来控制是否第一次调用  
  31.        if (force || (mBatteryProps.batteryStatus != mLastBatteryStatus ||  
  32.                mBatteryProps.batteryHealth != mLastBatteryHealth ||  
  33.                mBatteryProps.batteryPresent != mLastBatteryPresent ||  
  34.                mBatteryProps.batteryLevel != mLastBatteryLevel ||  
  35.                mPlugType != mLastPlugType ||  
  36.                mBatteryProps.batteryVoltage != mLastBatteryVoltage ||  
  37.                mBatteryProps.batteryTemperature != mLastBatteryTemperature ||  
  38.                mInvalidCharger != mLastInvalidCharger)) {  
  39.   
  40.            if (mPlugType != mLastPlugType) {  
  41.                if (mLastPlugType == BATTERY_PLUGGED_NONE) {  
  42.                   
  43.                    //不充电到充电  
  44.                    if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryProps.batteryLevel) {  
  45.                        dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;  
  46.                        logOutlier = true;  
  47.                        EventLog.writeEvent(EventLogTags.BATTERY_DISCHARGE, dischargeDuration,  
  48.                                mDischargeStartLevel, mBatteryProps.batteryLevel);  
  49.                        // make sure we see a discharge event before logging again  
  50.                        mDischargeStartTime = 0;  
  51.                    }  
  52.                } else if (mPlugType == BATTERY_PLUGGED_NONE) {  
  53.                    // 刚开始充电  
  54.                    mDischargeStartTime = SystemClock.elapsedRealtime();  
  55.                    mDischargeStartLevel = mBatteryProps.batteryLevel;  
  56.                }  
  57.            }  
  58.   
  59.            if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&  
  60.                    mPlugType == BATTERY_PLUGGED_NONE) {  
  61.                // We want to make sure we log discharge cycle outliers  
  62.                // if the battery is about to die.  
  63.                dischargeDuration = SystemClock.elapsedRealtime() - mDischargeStartTime;  
  64.                logOutlier = true;  
  65.            }  
  66.   
  67.            if (!mBatteryLevelLow) {  
  68.                // Should we now switch in to low battery mode?  
  69.                if (mPlugType == BATTERY_PLUGGED_NONE  
  70.                        && mBatteryProps.batteryLevel <= mLowBatteryWarningLevel) {  
  71.                    mBatteryLevelLow = true;  
  72.                }  
  73.            } else {  
  74.                // Should we now switch out of low battery mode?  
  75.                if (mPlugType != BATTERY_PLUGGED_NONE) {  
  76.                    mBatteryLevelLow = false;  
  77.                } else if (mBatteryProps.batteryLevel >= mLowBatteryCloseWarningLevel)  {  
  78.                    mBatteryLevelLow = false;  
  79.                } else if (force && mBatteryProps.batteryLevel >= mLowBatteryWarningLevel) {  
  80.                    // If being forced, the previous state doesn't matter, we will just  
  81.                    // absolutely check to see if we are now above the warning level.  
  82.                    mBatteryLevelLow = false;  
  83.                }  
  84.            }  
  85.            //发送电池状态变化的广播  
  86.            sendIntentLocked();  
  87.   
  88.            // Separate broadcast is sent for power connected / not connected  
  89.            // since the standard intent will not wake any applications and some  
  90.            // applications may want to have smart behavior based on this.  
  91.            if (mPlugType != 0 && mLastPlugType == 0) {  
  92.                mHandler.post(new Runnable() {  
  93.                    @Override  
  94.                    public void run() {  
  95.                        Intent statusIntent = new Intent(Intent.ACTION_POWER_CONNECTED);  
  96.                        statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);  
  97.                        mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);  
  98.                    }  
  99.                });  
  100.            }  
  101.            else if (mPlugType == 0 && mLastPlugType != 0) {  
  102.                mHandler.post(new Runnable() {  
  103.                    @Override  
  104.                    public void run() {  
  105.                        Intent statusIntent = new Intent(Intent.ACTION_POWER_DISCONNECTED);  
  106.                        statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);  
  107.                        mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);  
  108.                    }  
  109.                });  
  110.            }  
  111.   
  112.            if (shouldSendBatteryLowLocked()) {  
  113.                mSentLowBatteryBroadcast = true;  
  114.                mHandler.post(new Runnable() {  
  115.                    @Override  
  116.                    public void run() {  
  117.                        Intent statusIntent = new Intent(Intent.ACTION_BATTERY_LOW);  
  118.                        statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);  
  119.                        mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);  
  120.                    }  
  121.                });  
  122.            } else if (mSentLowBatteryBroadcast && mLastBatteryLevel >= mLowBatteryCloseWarningLevel) {  
  123.                mSentLowBatteryBroadcast = false;  
  124.                mHandler.post(new Runnable() {  
  125.                    @Override  
  126.                    public void run() {  
  127.                        Intent statusIntent = new Intent(Intent.ACTION_BATTERY_OKAY);  
  128.                        statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);  
  129.                        mContext.sendBroadcastAsUser(statusIntent, UserHandle.ALL);  
  130.                    }  
  131.                });  
  132.            }  
  133.   
  134.            //更新电池的LED  
  135.            mLed.updateLightsLocked();  
  136.   
  137.            // This needs to be done after sendIntent() so that we get the lastest battery stats.  
  138.            if (logOutlier && dischargeDuration != 0) {  
  139.                logOutlierLocked(dischargeDuration);  
  140.            }  
  141.   
  142.            mLastBatteryStatus = mBatteryProps.batteryStatus;  
  143.            mLastBatteryHealth = mBatteryProps.batteryHealth;  
  144.            mLastBatteryPresent = mBatteryProps.batteryPresent;  
  145.            mLastBatteryLevel = mBatteryProps.batteryLevel;  
  146.            mLastPlugType = mPlugType;  
  147.            mLastBatteryVoltage = mBatteryProps.batteryVoltage;  
  148.            mLastBatteryTemperature = mBatteryProps.batteryTemperature;  
  149.            mLastBatteryLevelCritical = mBatteryLevelCritical;  
  150.            mLastInvalidCharger = mInvalidCharger;  
  151.        }  
  152.    } 

转载于:https://my.oschina.net/u/2542649/blog/967525

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值