Android touch screen size - android

I would like to get the size of touch screen. For the reason, when I tested this code in the emulator the minimum values of X is 0(Y too, when pressing the 'corner' of the screen). But when I tested the code on a real devices, X shows displays 2000. So I want to read the absolute values of the screen. I think I need to get the 'minimun, maximum' values of screen. how can I read this value ?
main()
{
int fileno = open("/dev/input/event0",O_RDONLY),num_bytes;
char ev[50];
num_bytes=read(fileno,&ev,sizeof(struct input_event));
if(num_bytes<=0)
{
perror("Cannot access");
exit(FAILURE);
}
printf("%d\n",fileno);
printf("\nNumber of bytes read is %d\n string is%s\n",num_bytes,ev);
close(fileno);
}

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
This will tell you the real size of your screen in pixels, but you'll still need to account for density as well as action bar or title bar in figuring your actuall workable area.

Related

How to change the font size according to the screen size in android if I set the font sizes according to a specific phone?

I set all the font sizes in my .xml files so that they appear correctly on a specific phone (iPhone 11, to be exact). How do I change the font sizes according to screen sizes of individual phones?
For fonts in Android using sp is highly recommended.
For text views you might want to take a look at Android TextView AutoSizing
Use this library, it is pretty impressive and supports almost all resolutions and is very effective. Add these dependecies in gradle and sync gradle :
Benefit : Very easy to use, and text size change as per screen size.
Use this for view size(height, width, margin, etc.)
implementation 'com.intuit.sdp:sdp-android:1.0.6'
Usage :
android:layout_marginBottom="#dimen/_30sdp"
Use this for text sizes :
implementation 'com.intuit.ssp:ssp-android:1.0.6'
Usage :
android:layout_marginBottom="#dimen/_14ssp"
You first need to get the screen size ratio between iPhone 11 and the phone on which the app is running. Define a static variable in your MainActivity:
private static double SCREEN_SIZE_RATIO;
Then get iPhone 11's screen size. Don't use the raw dimensions because they don't take into account the fact that the screen does not cover the entire phone. Instead, take the pixel resolution and divide it by the ppi. Calculate iPhone 11's diagonal length and your target phone's diagonal length, and divide the latter by the former to get the screen size ratio.
private void calculateScreenSizeRatio() {
double iphone11Width = ((double) 828) / ((double) 326); // Values from https://www.apple.com/iphone-11/specs/
double iphone11Height = ((double) 1792) / ((double) 326);
double iphone11Diagonal = Math.hypot(iphone11Width, iphone11Height);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
double screenWidthPixels = displayMetrics.widthPixels;
double screenHeightPixels = displayMetrics.heightPixels;
double screenWidth = screenWidthPixels / displayMetrics.xdpi;
double screenHeight = screenHeightPixels / displayMetrics.ydpi;
double screenDiagonal = Math.hypot(screenWidth, screenHeight);
SCREEN_SIZE_RATIO = screenDiagonal / iphone11Diagonal;
}
Note that when calculating the diagonal length, the ratio of height-to-width is not taken into account, which introduces a slight inaccuracy.
Now, write a static function to get the font size (which was originally defined in the .xml), multiply it by the screen size ratio, and set the result to the new font size.
public static void setTextSize(TextView view) {
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (view.getTextSize() * SCREEN_SIZE_RATIO));
}
The getTextSize() function returns the size in pixels, that's why we set the size in pixels (using TypedValue.COMPLEX_UNIT_PX). Remember that both EditText and Button subclass from TextView, so this function can also be used for EditTexts and Buttons.
In your MainActivity, write a function similar to the following:
private void setTextSizes() {
setTextSize(emailEditText);
setTextSize(passwordEditText);
setTextSize(logInButton);
setTextSize(registerTextView);
setTextSize(invalidTextView);
setTextSize((TextView) findViewById(R.id.text_view_no_account));
}
In other activities, write a function similar to the following:
private void setTextSizes() {
MainActivity.setTextSize(amountEditText);
MainActivity.setTextSize((TextView) findViewById(R.id.edit_text_payment_method));
MainActivity.setTextSize((TextView) findViewById(R.id.add_button));
MainActivity.setTextSize(creditDebitCardTextView);
MainActivity.setTextSize(bankTransferTextView);
}
You can put any of your TextViews, EditTexts and Buttons in this function. Remember to cast your EditTexts and Buttons to (TextView) when using findViewbyId(), as I've done with edit_text_payment_method and add_button in the second code snippet.
Finally call setTextSizes() in onCreate() in each of your acivities, preferably after you have assigned the class variables.

Change the system display size programmatically Android N

Background: Android N comes with a feature to change system Display Size from settings, in addition to the previously present feature of changing Font Size.
Change Display Size:
Image Source: pcmag.com
Question:
If an app has android.permission.WRITE_SETTINGS permission to change the settings, there are ways to change the system font size programatically as mentioned in How to programmatically change font settings of Device: font style and font size?. However I couldn't find a way to change the display size programmatically. Is it possible?
What I've tried?
I've checked the possible options in the list of Settings.System convenience functions provided for changing settings programmatically.
Update:
I've opened a feature request for the same here: https://code.google.com/p/android/issues/detail?id=214124 . If you feel it would be useful please star it.
Just share my approach to tackle this requirement. I achieve this function by using the dirty Java reflection method - although it's not that elegant.
The main reference source code files are:
ScreenZoomSettings.java (https://github.com/aosp-mirror/platform_packages_apps_settings/blob/master/src/com/android/settings/display/ScreenZoomSettings.java)
DisplayDensityUtils.java (http://androidxref.com/9.0.0_r3/xref/frameworks/base/packages/SettingsLib/src/com/android/settingslib/display/DisplayDensityUtils.java)
WindowManagerGlobal.java (http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/view/WindowManagerGlobal.java)
And, follow the below steps, then you can get the required control:
Read ZoomScreenSettings.java's onCreate() and commit(). They demonstrate how to correctly get and set the density value into the framework.
Read DisplayDensityUtils.java. It shows how to use WindowManagerService to control the system density. Because we can't get the instance of DisplayDensityUtils via reflection, we need to understand which WindowManagerService methods are utilized.
Use reflection to get WindowManagerService's instance, and write a DisplayDensityUtils-like class into your project.
// Where wm is short for window manager
val wmGlobalClz = Class.forName("android.view.WindowManagerGlobal")
val getWmServiceMethod = wmGlobalClz.getDeclaredMethod("getWindowManagerService")
val wmService = getWmServiceMethod.invoke(wmGlobalClz)
val wmInterfaceClz = Class.forName("android.view.IWindowManager")
// Now, we already have the ability to do many things we want.
// For instance, to get the default density value.
val getInitialDisplayDensityMethod = wmInterfaceClz.getDeclaredMethod(
"getInitialDisplayDensity",
Integer.TYPE
)
val defaultDensity = getInitialDisplayDensityMethod.invoke(
wmService,
Display.DEFAULT_DISPLAY
) as Int
Set or get the density value with your DisplayDensityUtils-like class. One thing just to mention is that, if you want to pass an index value (e.g., 2 for large display size), please feed it to your DisplayDensityUtils-like class's mValues array to get the actual density value which is the right one to pass to the framework. Getting the current density index also applies the same concept.
In manifest, under application: android:configChanges="density"
In an activity/application:
public void adjustDisplayScale(Configuration configuration) {
if (configuration != null) {
Log.d("TAG", "adjustDisplayScale: " + configuration.densityDpi);
if(configuration.densityDpi >= 485) //for 6 inch device OR for 538 ppi
configuration.densityDpi = 500; //decrease "display size" by ~30
else if(configuration.densityDpi >= 300) //for 5.5 inch device OR for 432 ppi
configuration.densityDpi = 400; //decrease "display size" by ~30
else if(configuration.densityDpi >= 100) //for 4 inch device OR for 233 ppi
configuration.densityDpi = 200; //decrease "display size" by ~30
DisplayMetrics metrics = getResources().getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.densityDpi * metrics.density;
this.getResources().updateConfiguration(configuration, metrics);
}
}
Call it just after super.onCreate(..):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adjustDisplayScale( getResources().getConfiguration());
This will set the Display Size in-between the "Smaller" and "Small" settings of "Display Size" overriding any Display Size settings set by user.
It self-adjusts correctly for 4in, 5.5in, 6in etc devices.. but I'm sure there would a better way than using those if statements.
While referring Settings.System , there is a [putConfiguration(ContentResolver cr, Configuration config)](https://developer.android.com/reference/android/provider/Settings.System.html#putConfiguration(android.content.ContentResolver, android.content.res.Configuration)) method.
Use of this method is:
Convenience function to write a batch of configuration-related settings from a Configuration object.
In Configuration
This includes both user-specified configuration options (locale list and scaling) as well as device configurations (such as input modes, screen size and screen orientation).
Set configuration with SCREENLAYOUT_SIZE_MASK values for screen size.
It is:
The SCREENLAYOUT_SIZE_MASK bits define the overall size of the screen. They may be one of SCREENLAYOUT_SIZE_SMALL, SCREENLAYOUT_SIZE_NORMAL, SCREENLAYOUT_SIZE_LARGE, or SCREENLAYOUT_SIZE_XLARGE.
I hope its helps you.

Galaxy Note 5: Density Reduced Automatically

I created an app that relies on some screen metrics to function. It works great on all devices, except for the Galaxy Note 5. On the note 5 it reports the screen size of 1080x1920 while the screen is actually 1440x2560. I also see the following message in logcat:
"ActivityThread﹕ Switching default density from 560 to 420"
I'm finding the screen size by calling getWindowVisibleDisplayFrame in the following code:
Rect usable_rect = new Rect();
Window window = activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(usable_rect);
One other odd observation, if I use a package name other then my released app's package name the correct metrics are returned. Please help!
We finally found the answer to the Note 5 reducing the usable space for our app/game. It turned out Samsung is doing some optimization on the usable screen size for battery performance. The only way we found to use the true screen size of the display is by downloading Samsung's Game Tuner app and setting the mode to "Maximum Quality". It appears that without the Game Tuner app installed the default "Balanced Quality" is used, which results in the 1080p usable area.
https://play.google.com/store/apps/details?id=com.samsung.android.gametuner.thin&hl=en
Try this
Point size = new Point();
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(size);
mWindowWidth = size.x;
mWindowHeight = size.y;
} else {
Display d = w.getDefaultDisplay();
mWindowWidth = d.getWidth();
mWindowHeight = d.getHeight();
}

getDesiredMinimumHeight/Width() in 'Wallapper manager'

i looked at these 2 function in the documentation here
i want to get the desired wallaper dimensions,
running those functions on an SGS3 (1280x720) with stock launcher,
i got both minDesiredWidth + minDesiredHight: 1280x1280
same thing with a Note 3 (1920x1080) i got 1920x1920
i want to know the desired ratio of wallpaper the device wants, and i thought i would get it from those 2 functions.
both those devices stock launchers have a static background image of their respective screen resolutions, so why does getDesiredMinimumWidth doesn't give me 1280/1080 for each device respectively?
how do i know the proper ratio for the device?
This is the intended result of the methods, the code used in the WallpaperManager class is:
return sGlobals.mService.getHeightHint();
and
return sGlobals.mService.getWidthHint();
It isn't mentioned anywhere why they return the same value, but to get the true values of WxH, you should use:
Point displaySize = new Point();
getWindowManager().getDefaultDisplay().getRealSize(displaySize);
and refer to the values with int width = displaySize.x and int height = displaySize.y

Is their any way to find device is a mobile or a Tab in android ? how to remove Recent app button alone?

Is there any way to either remove the recent apps button in android 3.0 (I have a xoom) or clear the list? Is their any way to find device is, Mobile or Tab using java code.
Bcoz it breaks my policy app and allows people to switch device administrator if default Settings in that list. i am displaying my own launcher with out settings application.
So is their any way to disable Recent app button or to clear app thumbnail.
Please help me with any code sample or doc.Thanks in advance.
You've asked multiple questions. Here, I'm trying to answer your second question;
Is their any way to find device is, Mobile or Tab using java code.
You can use the screen size to determine whether your code is running on a tablet or mobile phone, see the code below;
public boolean isTablet() {
try {
// Compute screen size
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 should have a screen size greater than 6 inches
return size >= 6;
} catch(Throwable t) {
Log.error(TAG_LOG, "Failed to compute screen size", t);
return false;
}
}
Source: http://groups.google.com/group/android-developers/browse_thread/thread/d6323d81f226f93f

Categories

Resources