Android battery monitoring method
Usually there is a special battery controller chip (IC) in your phone which is always active even if the phone is switched off. This chip does the calculation on whatever base.

Android running on the main CPU just queries this special controller, retrieves and displays the values.

For a more detailed answer see How does charging a phone battery work?.