I have an object with many screen related methods (I put only two as an example here) as follows:
object AWScreen {
private lateinit var context: Context
fun init(context: Context) {
this.context = context
}
private fun getScreenHeightAlternative(oContext: Context): Int {
val display = oContext.resources.displayMetrics
return display.heightPixels
}
fun getScreenWidth(context: Context?): Int {
val size = Point()
var screenWidth = 0
try {
(context as Activity).windowManager.defaultDisplay.getRealSize(size)
screenWidth = size.x
} catch (e: NoSuchMethodError) {
e.printStackTrace()
}
return screenWidth
}
}
And I'm trying to initialise all dependencies (only context in this case) from an Application Class -when app starts- as follows:
@HiltAndroidApp
class AWApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
AWScreen.init(this)
}
}
But, as you can see, this way what I get is an application context rather than an activity context (what is needed to access resources).
I could just do:
AWScreen.init(this)
In any activity that depends on AWScreen onCreate, but I was trying to avoid this as AWScreen is widely used along my app and I don't want to repeat code, and in fact that's what Hilt (dependency injection) is meant for.
In resume, I have many custom classes (objects) where I need an activity context (rather than an application context) to access Resources (or any other class depending on the context), but I don't know how to provide it in a "dependency injection way" using Hilt, and avoiding the need to initialise that object's dependencies in every activity.
Edit 1:
As @مصطفى نعمه mentioned, I can access resources with any context (activity context as well as application context), but in my AWScreen class there are methods like the next:
private fun getSoftButtonsBarHeight(oActivity: Activity): Int {
val metrics = DisplayMetrics()
oActivity.windowManager.defaultDisplay.getMetrics(metrics)
val usableHeight = metrics.heightPixels
oActivity.windowManager.defaultDisplay.getRealMetrics(metrics)
val realHeight = metrics.heightPixels
return if (realHeight > usableHeight) realHeight - usableHeight else 0
}
where I need to access windowManager, and windowManager is only available in an activity context, so, to be clear, what I need to know is how to inject an activity context into a custom class.