In the case of android:anyDensity="true", the following method can be used to obtain
DisplayMetrics dm = MainActivity.getActivity().getResources().getDisplayMetrics(); int w_screen = dm.widthPixels; int h_screen = dm.heightPixels;
In the case of android:anyDensity="false", it is found that the obtained value is not the actual resolution. In debug, DisplayMetrics has two attributes, noncompatWidthPixels and noncompatHeightPixels, which show the actual resolution, but cannot directly use dm.noncompatWidthPixels. The method get is used, and the following methods need to be used to obtain it
int w_screen = 0; int h_screen = 0; try { Field field = DisplayMetrics.class.getDeclaredField("noncompatWidthPixels"); field.setAccessible(true); w_screen = field.getInt(dm); } catch (NoSuchFieldException e) { e.printStackTrace (); } catch (IllegalAccessException e) { e.printStackTrace (); }
h_screen can be obtained by a method similar to the above
Field imports is
import java.lang.reflect.Field;