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.
CodePudding user response:
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.