"Battery process from kernel to the Framework"

Source: Internet
Author: User
Tags constructor message queue stub throwable


"Battery process from kernel to the Framework"

Kernel:
Battery_common.c
Battery_meter.c
Switch_charging.c
Linear_charging.c
Power_supply_core.c
Power_supply_leds.c
Power_supply_sysfs.c

HAL: \system\core\healthd\batterymonitor.cpp
\system\core\healthd\batterypropertiesregistrar.cpp
\system\core\healthd\healthd.cpp
\system\core\healthd\healthd_board_default.cpp
\system\core\healthd\healthd_mode_android.cpp
\system\core\healthd\healthd_mode_charger.cpp

Native:frameworks\native\services\batteryservice\batteryproperties.cpp
Frameworks\native\services\batteryservice\batteryproperty.cpp
Frameworks\native\services\batteryservice\ibatterypropertieslistener.cpp
Frameworks\native\services\batteryservice\ibatterypropertiesregistrar.cpp

JNI (Java Native Interface is simply a Java program that calls a C + + write dynamic link library): none

Framework:
/api/current.txt
/core/java/android/os/batterymanager.java
/core/java/android/os/batteryproperties.java
/core/java/android/os/batterystats.java
/core/java/com/android/internal/app/ibatterystats.aidl
/core/java/com/android/internal/os/batterystatsimpl.java
/packages/systemui/src/com/android/systemui/batterymeterview.java
/services/java/com/android/server/batteryservice.java
/services/java/com/android/server/am/batterystatsservice.java
/include/batteryservice/batteryservice.h
/services/batteryservice/batteryproperties.cpp

Applications:
Ftm_battery.c


Kernel BATTERY_COMMON.C will create the node sys/class/power_supply/... and its properties.

============================================ Split Line ===========================================
Frameworks\base\service\java\com\android\server\systemserver.java

The Systemserver entry function in main () starts run ();
public static void Main (string[] args) {
New Systemserver (). run ();
}

Run () will call the
Create the system Service Manager.
Msystemservicemanager = new Systemservicemanager (msystemcontext);
Localservices.addservice (Systemservicemanager.class, Msystemservicemanager);

Start Services.
try {
Startbootstrapservices (); Create Activitymanagerservice,powermanagerservice Start Service
Startcoreservices (); Create Batteryservice
Startotherservices (); Call Mpowermanagerservice.systemready
} catch (Throwable ex) {

The Startbootstrapservices function performs some service creation, creating Activitymanagerservice,powermanagerservice,batteryservice

In Startotherservices () there is the following code, called Powermanagerservice.systemready (this systemready is implemented in Powermanagerservice.java)
try {
Todo:use Boot phase
Mpowermanagerservice.systemready (Mactivitymanagerservice.getappopsservice ());
} catch (Throwable e) {
REPORTWTF ("Making Power Manager Service ready", E);
}
Remember, this will be connected to the ①.
Frameworks\base\services\core\java\com\android\server\am\activitymanagerservice.java
The Batterystatsservice service is created in the constructor Activitymanagerservice () in the Activitymanagerservice class.

Frameworks\base\services\core\java\com\android\server\batteryservice.java (monitor the underlying battery event, broadcast a message that the battery has changed)
The OnStart () function in the Batteryservice class acquires the Batteryproperties service, creates Batterylistener, and listens for underlying state changes

public void OnStart () {
IBinder B = Servicemanager.getservice ("batteryproperties");
Final Ibatterypropertiesregistrar Batterypropertiesregistrar =
IBatteryPropertiesRegistrar.Stub.asInterface (b);
try {
Batterypropertiesregistrar.registerlistener (New Batterylistener ()); Create Batterylistener to monitor underlying battery state changes
} catch (RemoteException e) {
Should never happen.
}
if (Systemproperties.get ("Ro.mtk_ipo_support"). Equals ("1")) {
Intentfilter filter = new Intentfilter ();
Filter.addaction (ipo_power_on);
Filter.addaction (Ipo_power_off);
Mcontext.registerreceiver (New Broadcastreceiver () {//Register the broadcast recipient
@Override
public void OnReceive (context context, Intent Intent) {//onreceive () method, the broadcast sink is active only when it executes this method. When OnReceive () returns, it is inactive, note: In order to ensure the smooth user interaction process, some time-consuming operations to be put to the line thread
if (Ipo_power_on.equals (Intent.getaction ())) {
Miposhutdown = false;
Mipoboot = true;
Let Batteryservice to handle low battery warning.
Mlastbatterylevel = Mlowbatterywarninglevel + 1;
Update (MBATTERYPROPS);
} else
if (Ipo_power_off.equals (Intent.getaction ())) {
Miposhutdown = true;
}
}
}, filter);
}

    Publishbinderservice ("Battery", new Binderservice ());
    Publishlocalservice (Batterymanagerinternal.class, New LocalService ());
}

See if there is a change in the underlying state, the following battery_update will be called, below the Gbatterypropertiesregistrar->notifylisteners (*props);
Notifies listener that the props attribute state has changed.

Below is the HAL layer: (The notice above says listener is here to inform)
System\core\healthd\batterymonitor.cpp
Called Healthd_mode_ops->battery_update (&props) in the bool Batterymonitor::update (void) {} function in

This battery_update corresponds to the battery_update in the healthd_mode_ops structure in the System\core\healthd\healthd.cpp

static struct Healthd_mode_ops Android_ops = {
. init = Healthd_mode_android_init,
. preparetowait = healthd_mode_android_preparetowait,
. Heartbeat = Healthd_mode_nop_heartbeat,
. battery_update = Healthd_mode_android_battery_update,
};
Then look at the realization of healthd_mode_android_battery_update, in the System\core\healthd\healthd_mode_android.cpp

void Healthd_mode_android_battery_update (
struct Android::batteryproperties *props) {
if (Gbatterypropertiesregistrar! = NULL)
Gbatterypropertiesregistrar->notifylisteners (*props);

Return

}

Among them gbatterypropertiesregistrar->notifylisteners (*props); Here the direct call to Batterypropertiesregistrar's notifylisteners to notify listener props changed

Then look at where this notifylisteners was realized and find system\core\healthd\. Batterypropertiesregistrar.cpp (Create a battery property listener and register it with Android's system service)
One of the
void Batterypropertiesregistrar::notifylisteners (struct batteryproperties props) {
Mutex::autolock _l (Mregistrationlock);
for (size_t i = 0; i < mlisteners.size (); i++) {
Mlisteners[i]->batterypropertieschanged (props);
}
and look at the batterypropertieschanged (props) function,

It (batterypropertieschanged) in Frameworks\base\services\core\java\com\android\server\batteryservice.java

Private Final class Batterylistener extends Ibatterypropertieslistener.stub {
    @Override public
    Void Batterypropertieschanged (batteryproperties props) {
        final long identity = Binder.clearcallingidentity ();
        try {
            BatteryService.this.update (props);  Call Update (props)
        } finally {
            binder.restorecallingidentity (identity) in
   the Batteryservice Service;}}

Let's go back to the update function in Batteryservice.
private void Update (Batteryproperties props) {
Synchronized (MLock) {
if (!mupdatesstopped) {
Mbatteryprops = props;
if (Systemproperties.get ("Ro.mtk_ipo_support"). Equals ("1")) {
if (Miposhutdown)
Return
}
Process the new values.
if (mbootcompleted)
Processvalueslocked (FALSE); Implement a message that the broadcast battery has changed
} else {
Mlastbatteryprops.set (props);
}
}
}
Then look at the processvalueslocked () function,

private void Processvalueslocked (Boolean force) {
......
Let the battery stats keep track of the current level.
try {
Mbatterystats.setbatterystate (Mbatteryprops.batterystatus, Mbatteryprops.batteryhealth,//recorded here as ②; Setbatterystate will update the battery data and send the message Msg_report_power_change
Mplugtype, Mbatteryprops.batterylevel, Mbatteryprops.batterytemperature,
Mbatteryprops.batteryvoltage);
} catch (RemoteException e) {
Should never happen.
}
......
Sendintentlocked (); This is where the values are broadcast out.
......
}

private void sendintentlocked () {
Pack up the values and broadcast them to everyone
Final Intent Intent = new Intent (intent.action_battery_changed); Talk about intent: through intent, your program can express some kind of request or intention to Android, and Android will select the appropriate component to complete the request based on the intended content.
......
Mhandler.post (New Runnable () {
@Override
public void Run () {
Activitymanagernative.broadcaststickyintent (Intent, NULL, userhandle.user_all);
}
});
}

Here is the broadcast action_battery_changed out, waiting for receiver to listen to receive action_battery_changed broadcast message type, and then do the appropriate action.

Here we broadcast the Action_battery_changed broadcast message type, and we are looking at the receiver (Batteryreceiver and Batterystateservice above), as shown above, to hear the action after the broadcast.

Let's look at Powermanagerservice first.
Remember the Systemserver said before, see above ①.
The Systemserver will rise Powermanagerservice.systemready.
Powermanagerservice.java in the public void Systemready (Iappopsservice appops) function

public void Systemready (Iappopsservice appops) {
...
//Register for broadcasts from and components of the system.
Intentfilter filter = new Intentfilter ();
Filter.addaction (intent.action_battery_changed);
Filter.setpriority (intentfilter.system_high_priority);
Mcontext.registerreceiver (New Batteryreceiver (), filter, NULL, mhandler);//This creates a pair of action_battery_ Changed, the batteryreceiver will listen to this broadcast. (This binds the newly created broadcast Message receiver class object (Batteryreceiver) with the newly created Intentfilter class object and registers it with the system;)
...
Mcontext.registerreceiver (New Broadcastreceiver () {//Register broadcast recipients
@Override
public void onreceive (Context cont Ext, Intent Intent) {//onreceive () method, the broadcast sink is active only when it executes this method. When OnReceive () returns, it is inactive, note: In order to ensure the smooth user interaction process, some time-consuming operations to be put to the line thread

......
}
When Batteryreceiver receives the Action_battery_changed broadcast message type, look at the implementation in Batteryreceiver ().
Still in the Powermanagerservice.java.
Private Final class Batteryreceiver extends Broadcastreceiver {
@Override
public void OnReceive (context context, Intent Intent) {
Synchronized (MLock) {
Handlebatterystatechangedlocked (); Here's the handler function, let's see.
}
}
}

private void handlebatterystatechangedlocked () {
    mdirty |= dirty_battery_state;
    Updatepowerstatelocked ();    Here is the function in the diagram, "after receiving the broadcast message, execute updatepowerstatelocked ()"

}

The implementation of updatepowerstatelocked is as follows:
private void updatepowerstatelocked () {
......
try {
Phase 0:basic State Updates.
Updateispoweredlocked (Mdirty); It is determined whether it is USB Plug and unplug, low battery alarm and other events.
Updatestayonlocked (Mdirty);
Updatescreenbrightnessboostlocked (Mdirty);
......
}

/** * Updates the value of mispowered.
 * Sets dirty_is_powered if a change occurred.  */private void updateispoweredlocked (int dirty) {if ((Dirty & dirty_battery_state)! = 0) {Final Boolean
        waspowered = mispowered;
        Final int oldplugtype = Mplugtype;
        Final Boolean oldlevellow = Mbatterylevellow;
        mispowered = mbatterymanagerinternal.ispowered (Batterymanager.battery_plugged_any);
        Mplugtype = Mbatterymanagerinternal.getplugtype ();
        Mbatterylevel = Mbatterymanagerinternal.getbatterylevel ();
Mbatterylevellow = Mbatterymanagerinternal.getbatterylevellow (); 

......
if (waspowered! = mispowered | | Oldplugtype! = mplugtype) {//Determine if there is a pluggable
Mdirty |= dirty_is_powered;
......
}
......
if (waspowered! = mispowered | | Oldlevellow! = mbatterylevellow) {//Determine if it is a low battery alarm
if (oldlevellow! = Mbatterylevellow &&!mbatterylevellow) {
......
}
}
After judging  light up the screen
/* Still not finished, next to determine when the plug or low battery alarm
should do the corresponding processing operation, can take a look at this article http://www.360doc.com/content/13/1212/08/11627991_336500840.shtml
Baidu also search "updateispoweredlocked" This function name to look at the analysis.
*/

Look at the ② call Setbatterystate () function above in the private void processvalueslocked (Boolean force) function, which synchronizes the current battery status (update battery data) for track and sends a message msg_ Report_power_change.
In the Batterystatsservice.java
public void setbatterystate (final int status, final int health, final int plugtype,
Final int level, final int temp, final int volt) {
Enforcecallingpermission ();

    Batteryservice calls us here and we could update external state.
    It would is wrong//to the block such a low level service like Batteryservice on external stats like WiFi.
                Mhandler.post (New Runnable () {@Override public void run () {synchronized (mstats) {
                Final Boolean onbattery = Plugtype = = Batterystatsimpl.battery_plugged_none; if (mstats.isonbattery () = = Onbattery) {//the battery state have not changed, so we don ' t need to SYN
                    C External//stats immediately.
                    mstats.setbatterystatelocked (status, health, Plugtype, level, temp, volt);
                Return }}//Sync external stats first as the battery has changed states.
            If we don ' t sync//Immediately here, we are not collect the relevant data later.
            Updateexternalstats ("Battery-state", Update_all); Synchronized (mstats) {mstats.setbatterystatelocked (Status, health, Plugtype, level, temp, volt);
}
        }
    });
 } public void setbatterystatelocked (int status, int health, int plugtype, int. level, int temp, int volt) {

......
if (onbattery! = monbattery) {
Mhistorycur.batterylevel = (byte) level;
Mhistorycur.batterystatus = (byte) status;
Mhistorycur.batteryhealth = (byte) health;
Mhistorycur.batteryplugtype = (byte) plugtype;
Mhistorycur.batterytemperature = (short) temp;
Mhistorycur.batteryvoltage = (char) volt;
Setonbatterylocked (Elapsedrealtime, uptime, Onbattery, oldstatus, level);
} else {
......
}

void setonbatterylocked (Final long msecrealtime, final long Msecuptime, final Boolean onbattery,
Final int oldstatus, final int level) {
Boolean dowrite = false;
Message m = mhandler.obtainmessage (Msg_report_power_change);
M.arg1 = Onbattery? 1:0;
Mhandler.sendmessage (m); Send message Msg_report_power_change; SendMessage will drop message queued to the message queue, Mhandler will be built in the Batterystatsimpl constructor, as follows
}

Public Batterystatsimpl (File systemdir, Handler Handler, Externalstatssync externalsync) {
  ...
    Mexternalsync = Externalsync;
    Mhandler = new MyHandler (Handler.getlooper ());
  .....
    }

We can see handlemessage as message Msg_report_power_change, execute batterypowerchanged ();

In the Frameworks\base\services\core\java\com\android\server\am\activitymanagerservice.java
public void Batterypowerchanged (Boolean onbattery) {
When plugging in, update the CPU stats first before changing
The plug state.
Updatecpustatsnow (); Update CPU Status
Synchronized (this) {
Synchronized (mpidsselflocked) {
Monbattery = Debug_power? True:onbattery;
}
}
After that, you don't follow. That's the general process.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.