WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
Why the context
was used here?
Can any one explain?
According to official docs
Context
is the global information about an application environment. This is anabstract
class whose implementation is provided by theAndroid
system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
If you want to use the WIFI_SERVICE
which is a application-specific resource
you have to use the context
to retrieve the resource.
If you are inside activities or fragments, then you can call getApplicationContext().getSystemService(Context.WIFI_SERVICE)
directly without using the context
object because activities and fragments inherits from Context
class.
But if you are in a non Activity
or Fragment
class then you have to pass the context object from the activity or fragment (with constructors or setters) to that class in order to get application specific resources.
An example
public class AnyClass{
private Context context;
public AnyClass(Context context){
this.context = context;
}
...
WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}