Conversations.java

 1package eu.siacs.conversations;
 2
 3import android.app.Application;
 4import android.content.Context;
 5import android.content.SharedPreferences;
 6import android.preference.PreferenceManager;
 7
 8import androidx.appcompat.app.AppCompatDelegate;
 9
10import com.google.android.material.color.DynamicColors;
11import com.google.android.material.color.DynamicColorsOptions;
12
13import eu.siacs.conversations.utils.ExceptionHelper;
14
15public class Conversations extends Application {
16
17    @Override
18    public void onCreate() {
19        super.onCreate();
20        ExceptionHelper.init(getApplicationContext());
21        applyThemeSettings();
22    }
23
24    public void applyThemeSettings() {
25        final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
26        if (sharedPreferences == null) {
27            return;
28        }
29        applyThemeSettings(sharedPreferences);
30    }
31
32    private void applyThemeSettings(final SharedPreferences sharedPreferences) {
33        AppCompatDelegate.setDefaultNightMode(getDesiredNightMode(this, sharedPreferences));
34        var dynamicColorsOptions =
35                new DynamicColorsOptions.Builder()
36                        .setPrecondition((activity, t) -> isDynamicColorsDesired(activity))
37                        .build();
38        DynamicColors.applyToActivitiesIfAvailable(this, dynamicColorsOptions);
39    }
40
41    public static int getDesiredNightMode(final Context context) {
42        final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
43        if (sharedPreferences == null) {
44            return AppCompatDelegate.getDefaultNightMode();
45        }
46        return getDesiredNightMode(context, sharedPreferences);
47    }
48
49    public static boolean isDynamicColorsDesired(final Context context) {
50        final var preferences = PreferenceManager.getDefaultSharedPreferences(context);
51        return preferences.getBoolean(AppSettings.DYNAMIC_COLORS, false);
52    }
53
54    private static int getDesiredNightMode(
55            final Context context, final SharedPreferences sharedPreferences) {
56        final String theme =
57                sharedPreferences.getString(AppSettings.THEME, context.getString(R.string.theme));
58        return getDesiredNightMode(theme);
59    }
60
61    public static int getDesiredNightMode(final String theme) {
62        if ("automatic".equals(theme)) {
63            return AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
64        } else if ("light".equals(theme)) {
65            return AppCompatDelegate.MODE_NIGHT_NO;
66        } else {
67            return AppCompatDelegate.MODE_NIGHT_YES;
68        }
69    }
70}