In Android 11 two methods are deprecated
'getter for defaultDisplay: Display!' is deprecated. and 'getMetrics(DisplayMetrics!): Unit' is deprecated.
Hi @Sourav-21 thanks for contributing. I think the correct fix is to use getContext().getResources().getConfiguration().densityDpi see docs.
We should also change this for the other samples.
If you would like to make and verify those changes I can approve and merge.
Hi @stowy
getContext().getResources().getConfiguration().densityDpi method will not work in this case. getContext().getResources().getConfiguration().densityDpi will return corresponding to density resource qualifier like ldpi, mdpi etc. Please look at this stackoverflow answer.
Thanks @Sourav-21 point taken. Added some comments but we still need to update for other samples.
@stowy, resources.displayMetrics method isn't working on Android R too. I found this bug in AOSP sources.
I think proper implementation will be something like this-
DisplayMetrics outMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Display display = getContext().getDisplay();
display.getRealMetrics(outMetrics);
} else {
Display display = getWindowManager().getDefaultDisplay();
display.getMetrics(outMetrics);
}
return outMetrics.density;
@stowy , I also found in AOSP DisplayInfo source that density=densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE
So an alternative better solution is getContext().getResources().getConfiguration().densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE
I think that that latest option (using DENSITY_DEFAULT_SCALE) sounds good to me.
On Wed, Dec 9, 2020 at 2:21 PM Sourav Bagchi [email protected] wrote:
@stowy https://github.com/stowy , I also found in AOSP DisplayInfo https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/view/DisplayInfo.java source that density=densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE
So an alternative better solution is getContext().getResources().getConfiguration().densityDpi
- DisplayMetrics.DENSITY_DEFAULT_SCALE
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/googleads/googleads-mobile-android-examples/pull/276#issuecomment-741516850, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABNGOFAYUUHRVHUZFGQZERDST33NDANCNFSM4R5GCU7A .
I was wrong. To convert pixels into dp, we should divide pixels by a scaling factor and that scaling factor is dpi / 160.
getContext().getResources().getConfiguration().densityDpi method returns the screen dpi and after dividing dpi by 160 we get the scaling factor which is exactly same as outMetrics.density
And configuration().screenWidthDp method returns the screen width directly in dp.
I have tested these methods and work perfectly.
Any updates on this?