Android API 35+ Status/Navigation bar color/height from Java

shokarta

Neues Mitglied
So far I am using to set background color and get statusBar/navigationBar/cutout programaticaly from Java function, however its geting very old and most if its its deprecated in current Android API 35+.
So I googled as much as I could, used many exmaples to rerite to new functions, however the height of statusBar, navigationBar and cutout always returns zero, which is obvioulsy wrong.
In the following example I commented out by "OLD" how I use to use working code, by "NEW" which is not working new code, and by "NOTE" to is the open question I dont even know how to replace OLD by NEW.
Java:
package org.myapp.activity;

import org.qtproject.qt.android.QtNative;
import org.qtproject.qt.android.bindings.QtActivity;

import android.os.*;
import android.content.*;
import android.app.*;

import android.content.res.Resources;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

import android.view.Display;

import android.hardware.display.DisplayManager;
import android.view.Surface;
import android.view.View;
import android.view.DisplayCutout;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.graphics.Color;

import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsCompat.Type.InsetsType;


public class MyActivity extends QtActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCustomStatusAndNavigationBar();
    } // onCreate


    void setCustomStatusAndNavigationBar() {

        // First check sdk version, custom/transparent System_bars are only available after LOLLIPOP
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();

            // OLD: // The Window flag 'FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS' will allow us to paint the background of the status bar ourself and automatically expand the canvas
            // OLD: // If you want to simply set a custom background color (including transparent) for the statusBar/navigationBar, use the following addFlags call
            // OLD: window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            // NOTE: I found no mention if this is even needed when not using setStatusBarcolor() anymore, but will use WindowInsets.Type.statusBars() - my guess its not needed anymore

            // OLD: // The Window flag 'FLAG_TRANSLUCENT_NAVIGATION' will allow us to paint the background of the navigation bar ourself
            // OLD: // But we will also have to deal with orientation and OEM specifications, as the navigationBar may or may not depend on the orientation of the device
            // OLD: window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);     // DEPRECATED (NOTE: is this even needed as setStatusBarColor() and setNavigationBarColor() are deprecated?)

            // OLD: window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);                 // DEPRECATED
            // NOTE: Use WindowInsetsController instead (NOTE: is this even needed as setStatusBarColor() and setNavigationBarColor() are deprecated?)

            // OLD: Set StatusBar Transparent
            // OLD: window.setStatusBarColor(Color.TRANSPARENT);            // DEPRECATED
            // NOTE: Draw proper background behind WindowInsets.Type#statusBars()} instead

            // OLD: // Set NavigationBar to desired color (0xAARRGGBB) set alpha value to 0 if you want a solid color
            // OLD: window.setNavigationBarColor(Color.TRANSPARENT);        // DEPRECATED
            // NOTE: Draw proper background behind WindowInsets.Type#navigationBars() instead


            // OLD: // Statusbar background is now transparent, but the icons and text are probably white and not really readable, as we have a bright background color
            // OLD: // We set/force a light theme for the status bar to make those dark
            // OLD: View decor = window.getDecorView();
            // OLD: decor.setSystemUiVisibility(decor.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);          // DEPRECATED
            // NOTE: Use WindowInsetsController#APPEARANCE_LIGHT_NAVIGATION_BARS instead. I guess something like:
            window.insetsController?.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);     // for light mode, therefore dark foreground (text/icons)... NOTE: does it works on its own or do I need to set something specific, like addFlags() to make this work?
            //window.insetsController?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);     // for dark mode, therefore light foreground (text/icons)... NOTE: does it works on its own or do I need to set something specific, like addFlags() to make this work
            
            // NOTE: Use WindowInsetsController#APPEARANCE_LIGHT_STATUS_BARS instead. I guess something like:
            window.insetsController?.setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);     // for light mode, therefore dark foreground (text/icons)... NOTE: does it works on its own or do I need to set something specific, like addFlags() to make this work?
            //window.insetsController?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);     // for dark mode, therefore light foreground (text/icons)... NOTE: does it works on its own or do I need to set something specific, like addFlags() to make this work

        }
    }

    
    // NOTE: used info from: outdated https://medium.com/javarevisited/how-to-get-status-bar-height-in-android-programmatically-c127ad4f8a5d / unfortunately not link to github so I cant use whole example inluding includes, which I assume is my main problem
    public double statusBarHeight() {

        // OLD: Using Resources (still working, but preferable use current API solution)
        // double result = 0;
        // int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        // if (resourceId > 0) {
        //    result = getResources().getDimension(resourceId);
        // }
        // return result;


        // NEW: Using Window Insets (API 30+)
        WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
        double statusBarHeight = windowInsets.getInsets(WindowInsets.Type.statusBars()).top;    // returns 0 all the time, why?
    }

    public int safeAreaTop() {

        // OLD
        // DisplayCutout cutout = getWindow().getDecorView().getRootWindowInsets().getDisplayCutout();
        // if(cutout != null) {
        //     int cutoutHeight = cutout.getSafeInsetTop();
        //     if (cutoutHeight > 0) {
        //         return cutoutHeight;
        //      }
        // }
        // return 0;

        // NEW: Using Window Insets (API 30+)
        WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = windowInsets.getInsets(WindowInsets.Type.displayCutout()).top;   // returns 0 all the time, but not sure if correctly as I use only Android Simualtor, but if statusBarHeight() solution is not working, I assume also this does not work
        return cutoutHeight;
    }

    public double navigationBarHeight() {
    
        // OLD: Using Resources (still working, but preferable use current API solution)
        // double result = 0;
        // int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        // if (resourceId > 0) {
        //    result = getResources().getDimension(resourceId);
        // }
        // return result;


        // New: Using Window Insets (API 30+)
        WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
        double navigationBarHeight = windowInsets.getInsets(WindowInsets.Type.navigationBars()).bottom;     // returns 0 all the time, but not sure if correctly as I use only Android Simualtor without navigationBar, but if statusBarHeight() solution is not working, I assume also this does not work
        return navigationBarHeight;
    }

    public int getNavigationBarPosition() {

        Resources res = getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        boolean hasMenu = false;
        if (resourceId > 0) {
            hasMenu =  res.getBoolean(resourceId);
        }
        if (!hasMenu) {
            return -1;
        }


        // NOTE: https://stackoverflow.com/questions/69724946/getdisplay-return-display
        // Display display = getWindowManager().getDefaultDisplay();        // OLD: getDefaultDisplay() DEPRECATED
        DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);     // NEW solution, currently untested
        Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
        int rotation = display.getRotation();

        switch (rotation) {
            case Surface.ROTATION_90:
                return 1;
            case Surface.ROTATION_180:
                return 3;
            case Surface.ROTATION_270:
                return 2;
            default:
                return 0;
        }
    }
}

can I kindly ask for a check and explanation what did I do wrong in here along with the correction how the proper working code shall looks like?
PS: I am not an Java expert, I work in QT (so C++/QML), this is only thing needed for my app to manage from Java interface
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
BossLama Android Android Auto mit Linux Android & Cross-Platform Mobile Apps 1
A Was übersehe ich bei der Einrichtung eines neuen Android-Studios Android & Cross-Platform Mobile Apps 52
W Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.inter Android & Cross-Platform Mobile Apps 18
D Android Android Studio plus Gradle 7.5 bauen anders die apk Android & Cross-Platform Mobile Apps 0
J Benachrichtigung Freigabe ab Android 14 Android & Cross-Platform Mobile Apps 1
J Android Benachrichtigung zum Zeitpunkt ers Android & Cross-Platform Mobile Apps 15
J Das Beispiel von Android erzeugt Fehler Android & Cross-Platform Mobile Apps 8
J Zeitdifferenzen unter Android 7 (API < 26) berechnen Android & Cross-Platform Mobile Apps 4
W Netzwerk Verbindungen Java Android Android & Cross-Platform Mobile Apps 107
Z Android IntelliJ Android & Cross-Platform Mobile Apps 2
M Repository bei Room-Database in Android Studio (Java) Android & Cross-Platform Mobile Apps 2
Android App auf das eigene Handy bekommen Android & Cross-Platform Mobile Apps 3
Alex IV Android App erstellen Android & Cross-Platform Mobile Apps 3
OnDemand CrossPlatform Kotlin iOs/Android Datenverbrauch Android & Cross-Platform Mobile Apps 2
W In Android Studio Integer an andere activities übergeben Android & Cross-Platform Mobile Apps 2
wladp Android Studio Room Database Android & Cross-Platform Mobile Apps 1
N "Schöne" Datatable in Android und setzen von Parametern von Textview im Code Android & Cross-Platform Mobile Apps 5
N Android game programmieren Android & Cross-Platform Mobile Apps 5
T Android Studio: Einen Button in einer For Schleife verwenden Android & Cross-Platform Mobile Apps 2
K BLE Komunikation mit Android studio und esp32 Android & Cross-Platform Mobile Apps 5
G Android UDP Kommunikation Android & Cross-Platform Mobile Apps 1
M Paper DB wird in Android Studio nicht erkannt Android & Cross-Platform Mobile Apps 7
J Android zugrif auf Thread nach Handy drehen. Android & Cross-Platform Mobile Apps 10
T Android Android Augmented Faces in Java. Neue Landmarks erstellen Android & Cross-Platform Mobile Apps 1
K Android Android In-App-Purchase lädt nicht Android & Cross-Platform Mobile Apps 0
Besset Android http request an interne ip adresse funktioniert nicht Android & Cross-Platform Mobile Apps 8
J Is Android Development Head First Outdated? Android & Cross-Platform Mobile Apps 3
J Android Android Datenbankverbindung zum Raspberry Pi Android & Cross-Platform Mobile Apps 1
lolcore Android Studio -Download Documentation for Android SDK Android & Cross-Platform Mobile Apps 0
S Sinnvollste weg eine SQLite DB mit Android auslesen Android & Cross-Platform Mobile Apps 7
W Problem mit Android Studio Android & Cross-Platform Mobile Apps 0
W App Abo Android Android & Cross-Platform Mobile Apps 10
OSchriever Android Android MediaPlayer bei Anruf stoppen/pausieren Android & Cross-Platform Mobile Apps 2
OSchriever Auf onClick-Listener reagieren und Parameter übergeben (Android Studio) Android & Cross-Platform Mobile Apps 4
W removeNetwork Android App mit Spendenaktion fürs Tierheim! Android & Cross-Platform Mobile Apps 1
T Android R.string.test+i Problem Android & Cross-Platform Mobile Apps 2
P undefinierbarer Fehler Android Android & Cross-Platform Mobile Apps 8
T Android ArrayList sortieren mit 2 Werten ohne thencomparing , Wie? Android & Cross-Platform Mobile Apps 10
W Variable überschreiben (Android Studio) Android & Cross-Platform Mobile Apps 2
ruutaiokwu Android Selbst entwickelter SMTP-Client läuft auf PC, nicht aber auf Android Android & Cross-Platform Mobile Apps 9
ruutaiokwu Android Warum muss man bei Android Studio immer 2x auf "Run" klicken damit die App auf dem Gerät startet Android & Cross-Platform Mobile Apps 8
ruutaiokwu Android Wo das 'android.useAndroidX' property hinzufügen? Android & Cross-Platform Mobile Apps 8
ruutaiokwu Android In einem Android-“Spinner”-Element GLEICHZEITIG Bild (links) UND Text (rechts) anzeigen Android & Cross-Platform Mobile Apps 0
P Login und Registrierung Android Anzeige Android & Cross-Platform Mobile Apps 7
S Von JavaFx zu Android Android & Cross-Platform Mobile Apps 12
K Android to Pi | Websocket Problem Android & Cross-Platform Mobile Apps 3
ruutaiokwu Wie fügt man bei Android Studio .jar-Libraries zu einem Android-Java-Projekt hinzu? Android & Cross-Platform Mobile Apps 33
M Komponenten positionieren in Android Studio 3.6.3 Android & Cross-Platform Mobile Apps 1
M Android Studio - Property-Fenster einblenden Android & Cross-Platform Mobile Apps 1
M Android Studio - App auf dem Smartphone testen Android & Cross-Platform Mobile Apps 7
M Barrierefreie Appentwicklung für Android - Suche Codebeispiele Android & Cross-Platform Mobile Apps 8
M Android Studio - Configuration fehlt Android & Cross-Platform Mobile Apps 20
M Wo kann ich das Android SDK herunterladen / wie kann ich es installieren Android & Cross-Platform Mobile Apps 3
M Unsupported class file major version 57 - Fehlermeldung bei Android Studio Android & Cross-Platform Mobile Apps 27
ruutaiokwu Android Studio (SDK) ANDROID_SDK_ROOT-Variable? Android & Cross-Platform Mobile Apps 5
O Web API in Android (JAVA) einbinden Android & Cross-Platform Mobile Apps 3
J Android Studio macht seltsame Sachen Android & Cross-Platform Mobile Apps 2
J Android 9.1 aber android Studio findet API22 Android & Cross-Platform Mobile Apps 0
Dimax Web-Seite in native app convertieren mit Android Studio Android & Cross-Platform Mobile Apps 8
A Android Studio: while-Schleife beginnt nicht Android & Cross-Platform Mobile Apps 5
lolcore android studio: fehler bei laden des emulators Android & Cross-Platform Mobile Apps 10
J Android App - Browser öffnen und Text eingeben/Button click auslösen Android & Cross-Platform Mobile Apps 10
A Android-Studio: 2. Layout nach kurzer Zeit aufzeigen Android & Cross-Platform Mobile Apps 2
A jpg wird im Android Studio nicht akzeptiert Android & Cross-Platform Mobile Apps 3
J Android Studio - ArrayList - Selected Item ermitteln Android & Cross-Platform Mobile Apps 13
T Android SDK-Manager startet nicht in Eclipse Android & Cross-Platform Mobile Apps 5
T Bringen mir die Java-Basics irgendetwas für die Android-Programmierung Android & Cross-Platform Mobile Apps 4
J Was soll das bedeuten ? does not require android.permission.BIND_JOB_SERVICE permission Android & Cross-Platform Mobile Apps 7
A Android Studio: ImageView verpixelt Android & Cross-Platform Mobile Apps 2
J intend Service im Android Studio Android & Cross-Platform Mobile Apps 4
L Android Android Development eventuell mit Flutter Android & Cross-Platform Mobile Apps 1
S Android Layout - welchen Typ? Android & Cross-Platform Mobile Apps 3
T Fehler Android Studio: java.net.MalformedURLException: no protocol: http%3A%2F%2Fwww.mal ..... Android & Cross-Platform Mobile Apps 2
Arif Android Android Studio: Fehler beim Einbinden fremder Bibliothek? Android & Cross-Platform Mobile Apps 2
L Android Android Contacts DB auslesen Android & Cross-Platform Mobile Apps 1
A Android Studio - App mit Nearby Android & Cross-Platform Mobile Apps 1
L Android content URI Datei einlesen Android & Cross-Platform Mobile Apps 9
N Android Game Background Service Android & Cross-Platform Mobile Apps 11
Jackii Android Android Studio Error im Testlauf ohne zu programmieren Android & Cross-Platform Mobile Apps 9
B Android Probleme mit Android Studio Android & Cross-Platform Mobile Apps 6
Excess Android Service läuft nicht in Sandby weiter Android & Cross-Platform Mobile Apps 2
B Android Projekt für Android und IOS erstellen? Android & Cross-Platform Mobile Apps 5
J App funktioniert auf Android 5, auf 6 nicht Android & Cross-Platform Mobile Apps 2
J Android Snake Android & Cross-Platform Mobile Apps 15
J Android TaschenRechner Android & Cross-Platform Mobile Apps 22
I Das Problem mit der Tastatur... android:windowSoftInputMode="adjustPan" Android & Cross-Platform Mobile Apps 1
E Wie erhalte ich Zugriff auf das Microfon? (Android Studio) Android & Cross-Platform Mobile Apps 9
C Android Programmierung speziell oder einfach Java Buch kaufen? Android & Cross-Platform Mobile Apps 3
B Android Kein Zugriff auf Telefonspeicher (Android 6) Android & Cross-Platform Mobile Apps 1
T Android Equalizer für Android Android & Cross-Platform Mobile Apps 3
L Android Android Studio - Exportierte APK funktioniert nicht Android & Cross-Platform Mobile Apps 6
L Android Methode funktioniert nicht unter Android Android & Cross-Platform Mobile Apps 3
A Beginnen mit Serverkommunikatsion in Android Studio Android & Cross-Platform Mobile Apps 6
E Android Studio Android & Cross-Platform Mobile Apps 15
L Android Android Studio Setup killt Explorer Android & Cross-Platform Mobile Apps 3
K Android Videos rendern Android & Cross-Platform Mobile Apps 1
J Variable in strings.xml (Android Studio) Android & Cross-Platform Mobile Apps 0
B Android Android Studio lässt PC abstürzen Android & Cross-Platform Mobile Apps 3
B Android App Fehler Android & Cross-Platform Mobile Apps 21
J android Spinner funktioniert nicht Android & Cross-Platform Mobile Apps 14

Ähnliche Java Themen


Oben