Reputation: 25
I've been wondering about something in android development.
I have a class for requesting permissions to the device in an easier way for me, this class name is PermissionRequester
public class PermissionRequester{
int sdk;
Context context;
public PermissionRequester(Context context) {
this.context = context;
sdk = Build.VERSION.SDK_INT;
}
}
In a beginning, I was requesting a Context in my constructor for checking if the permission was allowed or denied by the user. Using Context didn't work, so I change "Context" to "Activity" and it worked.
public class PermissionRequester {
int sdk;
Activity activity;
public PermissionRequester(Activity activity) {
this.activity = activity;
sdk = Build.VERSION.SDK_INT;
}
}
In my MainActivity, I instanciate like this
PermissionRequester requester = new PermissionRequester(MainActivity.this);
So my question is the next:
- Why didn't I get a compile error in both cases using Context and Activity?
Upvotes: 0
Views: 116
Reputation: 1675
Add to DEX7RA's answer.
Another important Context is Appication, which is base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
I usually do application wide initialization in Application's OnCreate event, like creating database, log file, etc.
Upvotes: 0
Reputation: 3673
Context
is the Base Object. To be more precise an Activity
is a specialization of Context
. That's why you Activity
works in your case.
Take a look at this architecture of an Activity
:
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity
Upvotes: 2