Reputation: 303
Currently, I'm learning Android development and while learning I have come across several things like passing 'this' context, ActivityCompat, and ContextCompat. What is ActivityCompat and why, how, and where we should use it? I have also tried to read the documentation for it but as I am new to the android I'm not able to understand the way it was written in the documentation.
Also what is context parameter in android and what is it work and how to use it. As i often see that whenever context is asked in a method 'this' keyword is passed to it. Could you please explain it in easy to understand language?
Upvotes: 3
Views: 1629
Reputation: 93649
ActivityCompat is a Java class with only static members (similar to object
in Kotlin). This means you never instantiate it. It only provides helper functions.
ActivityCompat specifically provides alternatives to some of the functions in a regular Activity that can be used when the functionality you want to use is different across different versions of Android.
For example, Android 9 (SDK 28) apparently slightly modified the details of what happens when Activity.recreate()
is called. If your minSdkVersion
is set to lower than 28, you might want to ensure the behavior is the same even on devices that are running older versions of Android. To do this, instead of calling recreate()
in your Activity, you would call ActivityCompat.recreate(this)
.
There are various other "Compat" classes like this in the libraries, such as ViewCompat, WindowCompat, and WindowInsetsCompat.
Don't confuse ActivityCompat
with AppCompatActivity
, which is the class you normally will subclass to create your own Activities.
Upvotes: 3