In android it is possible to lock the screen orientation by adding this to the manifest :
android:screenOrientation="landscape"
But is it possible to lock within the size?
I want my app to be locked in portrait for phone format, and I want the user beeing able to use both portrait and landscape on a tablet format.
I've tried with screen size by using :
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
but it doesn't seem to work when I want to lock screen from code. Any idea of a good way to do this?
first check this answer
now you can change orientation like this
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (!tabletSize) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
You can get the diagonal Value of the device by following
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float yInches= metrics.heightPixels/metrics.ydpi;
float xInches= metrics.widthPixels/metrics.xdpi;
double diagonalInches = Math.sqrt(xInches*xInches + yInches*yInches);
After that you can check according to your need if you want the size of 5,5.5,6,6.5 or higher and change orientation according to need
if (diagonalInches>=6.5){
// 6.5inch device or bigger
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}else{
// smaller device
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
You can create a custom method to check the current screen density of phone,
public static boolean isTabLayout(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
//Device is a 10" tablet
return true;
} else if (smallestWidth > 600) {
//Device is a 7" tablet
return true;
}
return false;
}
To lock the screen orientation in portrait,
if (!isTabLayout(this)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
or in landscape,
if (!isTabLayout(this)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
Use This:
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void setOrientation(Context context){
if(!isTablet(contex){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I don't know exactly its working or not try this
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){
return "Tablet";
}else{
return "Mobile";
}
or look this once Determine if the device is a smartphone or tablet?
Related
I'd like to get the size of the screen of the phones but it keeps giving me wrong values, I already used
WindowManager windowmanager = (WindowManager)
getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
Display display = windowmanager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
float deviceWidth = displayMetrics.widthPixels;
float deviceHeight = displayMetrics.ydpi;
I tried this code too :
Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
// Note, screenHeightDp isn't reliable
// (it seems to be too small by the height of the status bar),
// but we assume screenWidthDp is reliable.
// Note also, dm.widthPixels,dm.heightPixels aren't reliably pixels
// (they get confused when in screen compatibility mode, it seems),
// but we assume their ratio is correct.
double screenWidthInPixels = (double)config.screenWidthDp *dm.density;
double screenHeightInPixels = screenWidthInPixels * dm.heightPixels / dm.widthPixels;
deviceWidth = (int)(screenWidthInPixels + .5);
deviceHeight = (int)(screenHeightInPixels + .5);
And also that :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Point realSize = new Point();
display.getRealSize(realSize);
deviceWidth= realSize.x;
deviceHeight = realSize.y;
}
But on my Samsung S7 on sdk 7.0 I got 1920x1080 that is wrong because on a S7 on sdk 6.0.1 I got 2560x1440 that is the real value.
I tried a lot of solution but found nothing good.
Thanks
Your code is correct. Just in case if you wondering why you get that values, it is because your phone will automatically set the default resolution size to 1920x1080 after updated to 7.0 (Nougat) to conserve the battery life. One of the new features in Nougat is display scaling option, where you can set your phone (in this case, S7) to 3 available modes (WQHD (2560x1440), FHD (1920x1080), and HD (1280x720)). Try go to Settings -> Display and change the settings to your needs. You can read more here: Galaxy S7 on Nougat defaults to 1080p
use this
getWindowManager().getDefaultDisplay().getHeight();
getWindowManager().getDefaultDisplay().getWidth();
This will work for sure.
try {
display.getRealSize(size);
height = size.y;
width=size.x;
} catch (NoSuchMethodError e) {
height = display.getHeight();
width=display.getWidth();
}
Try this link
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
The method below return a Point that contain display size (x as Width and y as Height):
public static Point checkDisplaySize(Context context) {
Point tempDisplaySize = new Point();
try {
WindowManager manager = (WindowManager) context().getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
display.getSize(tempDisplaySize);
Log.d("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
}
}
} catch (Exception e) {
Log.e("tmessages", e.getMessage(), e);
}
return tempDisplaySize;
}
P.S: This is the Code Telegram uses to get display size.
How can I calculate the screen size exactly under the consideration of Edge part?
Now, I'm developing custom keyboard and when it becomes visible, its size is calculated programmatically based on screen size.
What function I used calculate the screen size is like following.
public static Point getDimentionalSize(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int realWidth;
int realHeight;
if (Build.VERSION.SDK_INT >= 17){
//new pleasant way to get real metrics
DisplayMetrics realMetrics = new DisplayMetrics();
display.getRealMetrics(realMetrics);
realWidth = realMetrics.widthPixels;
realHeight = realMetrics.heightPixels;
} else if (Build.VERSION.SDK_INT >= 14) {
//reflection for this weird in-between time
try {
Method mGetRawH = Display.class.getMethod("getRawHeight");
Method mGetRawW = Display.class.getMethod("getRawWidth");
realWidth = (Integer) mGetRawW.invoke(display);
realHeight = (Integer) mGetRawH.invoke(display);
} catch (Exception e) {
//this may not be 100% accurate, but it's all we've got
realWidth = display.getWidth();
realHeight = display.getHeight();
Log.e("Display Info", "Couldn't use reflection to get the real display metrics.");
}
} else {
//This should be close, as lower API devices should not have window navigation bars
realWidth = display.getWidth();
realHeight = display.getHeight();
}
return new Point(realWidth, realHeight);
}
This function calculates screen size exactly in terms of pixels.
But when I try it on Samsung Galaxy Note Edge, the resulted screen width composes device's Edge part also.
I'd like to exclude it from screen size. (if portrait, from width, otherwise, from height)
What's the solution?
You can try this
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
I'm writing an Android app with a transparent navigation bar. To adjust the layout accordingly, I need to know whether the device has software or hardware buttons.
During my research I came across the following solutions:
boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
This approach does not work on some new devices like the Samsung Note 4 or the HTC One which do not have a menu key, but still have hardware buttons.
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
boolean hasHardwareButtons = hasBackKey && hasHomeKey;
This does not work as well, because some devices like the Sony Xperia Z3 Compact return true although it has a software navigation bar.
Is there any reliable way to find out whether there are physical buttons or a software navigation bar?
See this answer. You can get the real height of the display in pixels, and then get the height available to your app, and figure out if the device has an on-screen navigation bar with these values.
The answer posted here did the trick. Just for completeness, here is the code I am using now:
private static boolean hasImmersive;
private static boolean cached = false;
#SuppressLint ("NewApi")
public static boolean hasImmersive(Context ctx) {
if (!cached) {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
hasImmersive = false;
cached = true;
return false;
}
Display d = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
DisplayMetrics realDisplayMetrics = new DisplayMetrics();
d.getRealMetrics(realDisplayMetrics);
int realHeight = realDisplayMetrics.heightPixels;
int realWidth = realDisplayMetrics.widthPixels;
DisplayMetrics displayMetrics = new DisplayMetrics();
d.getMetrics(displayMetrics);
int displayHeight = displayMetrics.heightPixels;
int displayWidth = displayMetrics.widthPixels;
hasImmersive = (realWidth > displayWidth) || (realHeight > displayHeight);
cached = true;
}
return hasImmersive;
}
I need to disable a certain button in my app if the screen size of the Android device is considered SMALL (320dp x 426dp units). I am currently using:
if (activity.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
//Is small size
} else {
//Is not small size
}
to determine the screen size of the device, however this never seems to enter the condition of Configuration.SCREENLAYOUT_SIZE_SMALL. I did printouts and found that the value actually equates to Configuration.SCREENLAYOUT_SIZE_NORMAL!
The answer from Alex Lockwood here: How do I get the ScreenSize programmatically in android is my reference for this solution, but as J R P noted on his answer, everything seemed to equate to Configuration.SCREENLAYOUT_SIZE_NORMAL just like mine.
How do I reliably define the screen size of the device? I am currently testing on a Samsung Galaxy S3, and by all means this should have been a "small" device.
Thanks in advance,
Rei
Try This TO Display Dimensions In Pixels
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
For More Use This StackQuestion
here comes two functions to get screen size W and H
public static int getScreenSizeW(Context context) {
int screenSizeW = 320;//default
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
try {
screenSizeW = DisplayMetrics.class.getField("widthPixels").getInt(displayMetrics);
} catch (Exception e) {
}
return screenSizeW;
}
public static int getScreenSizeH(Context context) {
int screenSizeH = 480;//default
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
try {
screenSizeH = DisplayMetrics.class.getField("heightPixels").getInt(displayMetrics);
} catch (Exception e) {
}
return screenSizeH;
}
and here comes another way to get the display size:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
size.x = display.getWidth();
size.y = display.getHeight();
Try this code..
int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
String toastMsg;
switch(screenSize) {
case Configuration.SCREENLAYOUT_SIZE_LARGE:
toastMsg = "Large screen";
break;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
toastMsg = "Normal screen";
break;
case Configuration.SCREENLAYOUT_SIZE_SMALL:
toastMsg = "Small screen";
break;
default:
toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
Also have a look at
Use the below code.
public boolean isPhone(Context activityContext) {
if(null!=activityContext)
{
boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
boolean large = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
return (xlarge || large)?false:true;
}
return false;
}
My case is that the logic is same for both Phone and Tablet. But there is slight difference in the layout. And I tried with the following code
public static boolean findoutDeviceType(Context context)
{
return (context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK)>=
Configuration.SCREENLAYOUT_SIZE_LARGE;
}
Samsung Tab 10" has the resolution of 1280 * 800 and S3 has the resolution of 1270 * 720. And this code returns the Size as XLarge for both the Tab and Phone as its criteria for checking is > 960 * 720.
I have tested inserting the respective UI in the layout folder in Res as Layout, Layout-Large and Layout-xLarge . But this didn't effect in anyway. while checking it took the UI from the Layout folder.
Anyway even though I place the UI in the different layout folders, I have to check them in the class file to set the respective ContentView.
Is there any other way to find it?
This subject is discussed in the Android Training:
http://developer.android.com/training/multiscreen/screensizes.html#TaskUseSWQuali
Here is implementation,
Credit goes to ol_v_er for this simple and easy approach.
Some additional Information
You have now flag indicate whether your application is running on phone or tablet.
I have created two packages to handle UI and it's functionality,
com.phone
com.tablet
And you redirect control to your needed package
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
// do something
//Start activity for tablet
} else {
// do something else
//Start activity for phone
}
Refer
Note :I think for both 10 inch and 7 inch screen app take resources from res/values-sw600dp/ . But To be more specific I think for 10 inch tablet screen we can use res/values-sw720dp/
<resources>
<bool name="isTablet">true</bool>
</resources>
Try this
public boolean isTablet(Context context) {
boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
return (xlarge || large);
}
It will return true if you are using a tablet. It has been checked on Samsung Galaxy Tab 7" and Samsung Galaxy S3.
For example, you could set some res-values folder:
res/values-xlarge
res/values-large
res/values-sw600dp
etc. Then You could declare a boolean for each one:
<resources>
<bool name="isXLarge">true</bool>
</resources>
or
<resources>
<bool name="isLarge">true</bool>
</resources>
you can get the value by
boolean xlargeValue = getResources().getBoolean(R.bool.isXlarge);
boolean largevalue = getResources().getBoolean(R.bool.isLarge);
boolean tabletValue = getResources().getBoolean(R.bool.sw620dp):
Try this code your app is working device phone or tablet easy to fine call the method oncreate() inside
isTabletDevice(activity)
private static boolean isTabletDevice(Context activityContext) {
boolean device_large = ((activityContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE)
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (device_large) {
//Tablet
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_TV){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_HIGH){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_280){
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_400) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_XXHIGH) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_560) {
return true;
}else if(metrics.densityDpi == DisplayMetrics.DENSITY_XXXHIGH) {
return true;
}
}else{
//Mobile
}
return false;
}
Old question, but this might help someone.
If you want to find out if device is tablet (screen lager than 7"), or phone, you can use this util method:
Kotlin
fun isTablet(): Boolean {
return App.instance.resources.configuration.smallestScreenWidthDp >= 600
}
Java
public static Boolean isTablet(){
return App.instance.resources.configuration.smallestScreenWidthDp >= 600
}
App.instance is aplication instance.
public boolean isTablet() {
try {
// Compute screen size
Context context = this;
DisplayMetrics dm =
context.getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.xdpi;
float screenHeight = dm.heightPixels / dm.ydpi;
double size = Math.sqrt(Math.pow(screenWidth, 2) +
Math.pow(screenHeight, 2));
// Tablet devices have a screen size greater than 6
inches
return size >= 6;
} catch(Throwable t) {
Log.e("Failed to compute screen size", t.toString());
return false;
}
}
Try this code. You can get the screen inches, On the basis of size you can get the tablet or android device
String inputSystem;
inputSystem = android.os.Build.ID;
Log.d("hai",inputSystem);
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
Log.d("hai",width+"");
Log.d("hai",height+"");
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(width/dm.xdpi,2);
double y = Math.pow(height/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);
Log.d("hai","Screen inches : " + screenInches+"");
Use different resource files rather than trying to determine it programmatically. This will be enough for the majority of cases and is what the documentation recommends.
See my fuller answer here.
All other questions use resource qualifiers and methods, which do not represent the PHYSICAL size of the device, but the AVAILABLE screen size. For example, in the multi-window mode, the system will get resources from the "values" folder instead of "values-large", because the available screen size for the app became smaller. To determine, whether the physical device is a tablet or phone, use the following method (I use 640x480dp as the minimum size for a tablet, which is the definition of large devices, feel free to change these constants):
fun isTablet(context: Context): Boolean {
val outSize = Point()
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getRealSize(outSize)
outSize.x = pxToDp(windowManager, outSize.x)
outSize.y = pxToDp(windowManager, outSize.y)
val shorterSideDp: Int
val longerSideDp: Int
if (outSize.x > outSize.y) {
shorterSideDp = outSize.y
longerSideDp = outSize.x
} else {
shorterSideDp = outSize.x
longerSideDp = outSize.y
}
return shorterSideDp > 480 && longerSideDp > 640
}
Function for converting PX to DP:
#Dimension(unit = Dimension.DP)
fun pxToDp(windowManager: WindowManager, #Dimension(unit = Dimension.PX) px: Int): Int {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
return (px / displayMetrics.densityDpi.toFloat() * DisplayMetrics.DENSITY_DEFAULT).roundToInt()
}
This is working perfectly well in my app:
private boolean isPhoneDevice(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}