How to get current AppCompatDelegate mode if auto is used by default

I have this activity:

package com.nkdroid.daynighttheme;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.widget.TextView;

public class ModeActivity extends AppCompatActivity {

    private TextView txtModeType;
    int modeType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_mode);
        txtModeType = (TextView) findViewById(R.id.txtModeType);
        modeType = AppCompatDelegate.getDefaultNightMode();

        if (modeType == AppCompatDelegate.MODE_NIGHT_AUTO) {
            txtModeType.setText("Default Mode: Auto");
        } else if (modeType == AppCompatDelegate.MODE_NIGHT_YES) {
            txtModeType.setText("Default Mode: Night");
        } else if (modeType == AppCompatDelegate.MODE_NIGHT_NO) {
            txtModeType.setText("Default Mode: Day");
        }
    }
}`

Is it possible to activate the mode (day or night) if the default mode is set to AUTO ?

+10
source share
2 answers

You can get the current mode using the following code,

int currentNightMode = getResources().getConfiguration().uiMode
        & Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
    case Configuration.UI_MODE_NIGHT_NO:
        // Night mode is not active, we're in day time
    case Configuration.UI_MODE_NIGHT_YES:
        // Night mode is active, we're at night!
    case Configuration.UI_MODE_NIGHT_UNDEFINED:
        // We don't know what mode we're in, assume notnight
}

The following article by Chris Banes explains this beautifully.

+21
source

If you are a kotlin developer, you can use the code below to check what mode your application is running in.

val mode = context?.resources?.configuration?.uiMode?.and(Configuration.UI_MODE_NIGHT_MASK)
when (mode) {
    Configuration.UI_MODE_NIGHT_YES -> {}
    Configuration.UI_MODE_NIGHT_NO -> {}
    Configuration.UI_MODE_NIGHT_UNDEFINED -> {}
}

For more information on dark theme modes, see

https://github.com/googlesamples/android-DarkTheme/

0

Source: https://habr.com/ru/post/1665290/


All Articles