I am using the following function in one of my activities of my app:
public static float convertDpToPixel(float dp, Context context){
return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
What context should I use?
Application Context: tied to the Lifecycle of an Application
Activity Context: tied to the life cycle of activity
Base Context: the base context as set by the constructor or setBaseContext
I have done it like this and it seems to work:
In my_activity.java:
float conversion = convertDpToPixel(10, this);
But also I could do the following:
float conversion = convertDpToPixel(10, getApplicationContext());
And also the following:
float conversion = convertDpToPixel(10, getBaseContext());
I think that in this specific case it doesn't really matter as it will get the resources of the app and it is included in all the contextes types but I would like to ensure what I am saying. Thanks
All of three you can use in this case. Context usually use to get resource or launch some system service, and I found a context explain in this website https://www.jianshu.com/p/94e0f9ab3f1d, here is the picture he explain when each context can be use: (不推荐 mean not recommended)
Most of case you can use Application, Activity, and Service context, but beside some scene, like show dialog,start activity, and layout inflation. A dialog need to build base on a activity, so you can't use other two type context. This case seems to be load resource values, so you can use all of three.
Other information about context: Difference between Activity Context and Application Context, https://web.archive.org/web/20150329210012/https://possiblemobile.com/2013/06/context/.