Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help using batterymanager on android studio

https://stackoverflow.com/a/47020822/12620073 I tried to use this solution in my code in order to check whether the phone is being charged or not. However in this line –

BatteryManager myBatteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);

I don’t understand what should be the class of the term "context" nor what it is exactly. I’ll really appreciate it if anyone will explain this to me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Context is any class that derives from the Context class. The 3 main types are Activities, Applications and Services. So if you run that code in an Activity, it would be this.getSystemService(). If you run it in another class, you need to pass in a context to that class. Generally it will be your Activity, or your Application (generally accessed by using activity.getApplicationContext() ). For getSystemService, running it on any convenient Context is acceptable.

In general, when passing a context to a method prefer to pass the Application context. This is to protect against that class saving an instance of the context, as doing that to an Activity can in some cases cause memory leaks.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading