How to disable night mode in my application even if night mode is enable in android 9.0 (pie)?

I created my application before the android pie has been released, in every layout I put android: background = "white" it works fine in every device, but when my brother installed the application and enabled night mode my application becomes a disaster with one single move, everything turns into back and white movie.

<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/COLOR_PRIMARY</item>
    <item name="colorPrimaryDark">@color/COLOR_PRIMARY</item>
    <item name="colorAccent">@color/COLOR_PRIMARY</item>
    <item name="cardViewStyle">@style/CardView</item>
    <item name="android:fontFamily">@font/helvetica</item>
</style>

my color primary is red.


Solution 1:

You can put this, at the first line in the onCreate method of your launcher activity.

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

Solution 2:

Tested using Xiaomi Note 8 Pro MIUI 12.0.2 Android 10

Adding AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); to MainActivity.onCreate(); doesn't seems to be working

The working solution was to add <item name="android:forceDarkAllowed">false</item> inside our main AppTheme block in styles.xml

Example:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
</style>

Update for InputMethodService :

For InputMethodService / Maybe if we inflate layout in any Service
I found when in Dark Mode - Xiaomi MIUI 12.0.3 there's a Black color which gets inverted into White.
To prevent the inversion, so Black color will still be Black be sure to set a theme in InputMethodService.

At onCreate() before super.onCreate() call these methods

  • getApplication().setTheme()
  • setTheme()

For your information, I'm passing Light Theme (Theme.MaterialComponents.Light.NoActionBar) which have android:forceDarkAllowed=false.
In my case for InputMethodService just calling getApplication().setTheme() is not enough to prevent the inversion.

Solution 3:

In themes.xml change:

<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

to

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.DarkActionBar">