Reputation: 63
My application consists of three classes :
Map contains google map methods and DataWriter contains File writer methods as long with a write storage permission check on runtime IsWriteEnabled().
I call IsWriteEnabled() from Map so I can check If I have permissions with the following way:
class Map : Fragment() , OnMapReadyCallback {
private lateinit var mdataWriter: DataWriter
// a lot of code removed
override fun onMapReady(googleMap: GoogleMap) {
mdataWriter = DataWriter(requireContext())
mdataWriter.isWriteEnable()
}
here is my DataWriter.kt
class DataWriter(val context: Context): AppCompatActivity(){
fun isWriteEnable(): Boolean {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
context as Activity,
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE
),
WRITE_REQUEST_CODE
)
} else {
Log.e("DB", "PERMISSION GRANTED")
}
return true
}
Is there a better way to pass context to a class that its not attached to main activity? Is the call to the method as it should be?
Upvotes: 2
Views: 6895
Reputation: 3331
You are free to pass a Context
to a class that its not attached to an Activity
in any way you like. Passing it through the class's constructor is a good practice (dependency injection), but only in the case where your class needs a Context
to fully function correctly. If you need a Context
to use only in a specific method, might as well pass it as an argument to the method.
The most important thing you have to be aware here is that an Activity
has a finite life cycle. If you keep a reference to an Activity Context
in a class that will outlive that Activity
, you will create a memory leak: the garbage collector will not be able to destroy that Activity
because there's a reference to it somewhere. This is why people usually prefer to handle an Application Context
instead, which will always outlive any class you can create.
Now, a correction to your code: don't extend AppCompatActivity
just to inherit ActivityCompat
. By extending AppCompatActivity
, you're granting the class access to a lot of life cycle management, resource handling and user interaction methods that have nothing to do with your class. AppCompatActivity
is supposed to be extended by Activities
only. Otherwise, its name would not end with Activity :)
As components that handle user interaction, asking for permissions is a responsibility of the Activity
or Fragment
, so just ask for the permission either in Map
or MainActivity
. Also, I'm assuming that Map
is indeed doing what a Fragment
is supposed to do, and you're not just extending Fragment
to get access to some Fragment
methods :)
Upvotes: 5