From 7504d9aa786877255256f05fa338b91507d9828a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonhard=20K=C3=BCnzler?= Date: Sat, 9 Apr 2022 22:06:31 +0200 Subject: [PATCH] Use built-in tools for darkmode if supported --- app/build.gradle | 1 + .../whatsappwebtogo/WebviewActivity.java | 28 ++++++++++++------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 47adf62..ddafdbd 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -28,4 +28,5 @@ android { dependencies { implementation 'androidx.appcompat:appcompat:1.3.0' implementation 'com.google.android.material:material:1.3.0' + implementation 'androidx.webkit:webkit:1.4.0' } diff --git a/app/src/main/java/io/kuenzler/whatsappwebtogo/WebviewActivity.java b/app/src/main/java/io/kuenzler/whatsappwebtogo/WebviewActivity.java index 09923ed..e7dafd1 100644 --- a/app/src/main/java/io/kuenzler/whatsappwebtogo/WebviewActivity.java +++ b/app/src/main/java/io/kuenzler/whatsappwebtogo/WebviewActivity.java @@ -50,12 +50,15 @@ import androidx.core.content.ContextCompat; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; +import androidx.webkit.WebSettingsCompat; +import androidx.webkit.WebViewFeature; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import java.util.Arrays; import java.util.Locale; +import java.util.Objects; public class WebviewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @@ -567,17 +570,22 @@ private void loadWhatsapp() { } public void addDarkMode(final WebView mWebView) { - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - getWindow().setNavigationBarColor(Color.BLACK); - getWindow().setStatusBarColor(Color.BLACK); - try{ getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); - } catch (NullPointerException ignored) {} - } + getWindow().setNavigationBarColor(Color.BLACK); + getWindow().setStatusBarColor(Color.BLACK); - mWebView.loadUrl("javascript:(" + - "function(){ " + - "try { document.body.classList.add('dark') } catch(err) { }" + - "})()"); + Objects.requireNonNull(getSupportActionBar()).setBackgroundDrawable(new ColorDrawable(Color.BLACK)); + + if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { + WebSettingsCompat.setForceDark(mWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON); + if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK_STRATEGY)) { + WebSettingsCompat.setForceDarkStrategy(mWebView.getSettings(), WebSettingsCompat.DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING); + } + } else { + mWebView.loadUrl("javascript:(" + + "function(){ " + + "try { document.body.classList.add('dark') } catch(err) { }" + + "})()"); + } } public void setContentSize(final WebView mWebView){