-1

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

sacacorchos
  • 163
  • 9

1 Answers1

-1

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) enter image description here

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/.

Community
  • 1
  • 1
Jeff Lin
  • 19
  • 5
  • You should not use the Application context to load resource values, as the resource set may be different in the Activity context. For example, an Activity may have a theme that alters it. It will work (it won't crash), but it may not be right. – Gabe Sechan Dec 27 '22 at 03:24
  • @GabeSechan according to your answer I think I should use this one: float conversion = convertDpToPixel(10, this); Is that right? – sacacorchos Dec 27 '22 at 12:24