android 获取屏幕信息

两种方法,

1.

WindowManager windowManager = getWindowManager();
		Display defaultDisplay = windowManager.getDefaultDisplay();
		int height = defaultDisplay.getHeight();
		int width = defaultDisplay.getWidth();
2、
DisplayMetrics displayMetrics=new DisplayMetrics();
		WindowManager windowManager = getWindowManager();
		Display defaultDisplay = windowManager.getDefaultDisplay();
		defaultDisplay.getMetrics(displayMetrics);
		int widthPixels = displayMetrics.widthPixels;
		int heightPixels = displayMetrics.heightPixels;


补充,如果getWindowManager获取不到,可用 


WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);




再贴一段代码

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        int width = defaultDisplay.getWidth();
        int height = defaultDisplay.getHeight();



        DisplayMetrics displayMetrics = new DisplayMetrics();
        defaultDisplay.getMetrics(displayMetrics);

        int widthPixels = displayMetrics.widthPixels;
        int heightPixels = displayMetrics.heightPixels;


        int widthPixels1 = getResources().getDisplayMetrics().widthPixels;
        int heightPixels1 = getResources().getDisplayMetrics().heightPixels;
        float density = getResources().getDisplayMetrics().density;
        int densityDpi = getResources().getDisplayMetrics().densityDpi;


        Log.e("mrpeng","width::"+width+"height::"+height);

        Log.e("mrpeng","widthPixels::"+widthPixels+"heightPixels::"+heightPixels);
        Log.e("mrpeng","widthPixels1"+widthPixels1+"heightPixels1++"+heightPixels1);
        Log.e("mrpeng","density"+density);
        Log.e("mrpeng","densityDpi"+densityDpi);


    }
}
以上结果是一致的,至于区别,以后再做计较






 
 

你可能感兴趣的:(安卓学习)