/* * Copyright (c) 2024 Amin Bandali * * This file is part of Kelar Keyboard. * * Kelar Keyboard is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Kelar Keyboard is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Kelar Keyboard. If not, see * . */ package org.kelar.inputmethod.latin.utils; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.util.Log; import org.kelar.inputmethod.compat.BuildCompatUtils; import org.kelar.inputmethod.latin.BuildConfig; public class PreferenceUtils { static final String TAG = PreferenceUtils.class.getSimpleName(); private static final int DOES_NOT_EXIST = -1; private static final String PREF_MOVEDTODPS_SUFFIX = "_movedtodps"; public static SharedPreferences getSharedPreferences(Context context, String name, int mode) { Context storageContext = context; if (BuildCompatUtils.EFFECTIVE_SDK_INT >= Build.VERSION_CODES.N) { final Context deviceContext; if (context.isDeviceProtectedStorage()) { deviceContext = context; } else { deviceContext = context.createDeviceProtectedStorageContext(); } final String pref_name = name + PREF_MOVEDTODPS_SUFFIX; if (deviceContext.getSharedPreferences(name, mode) .getInt(pref_name, DOES_NOT_EXIST) == DOES_NOT_EXIST) { if (deviceContext.moveSharedPreferencesFrom(context, name)) { deviceContext.getSharedPreferences(name, mode) .edit() .putInt(pref_name, BuildConfig.VERSION_CODE) .apply(); } else { Log.w(TAG, String.format("Failed to migrate shared preferences %s.", name)); } } storageContext = deviceContext; } return storageContext.getSharedPreferences(name, mode); } public static SharedPreferences getSharedPreferences(Context context, String name) { return getSharedPreferences(context, name, getDefaultSharedPreferencesMode()); } public static SharedPreferences getDefaultSharedPreferences(Context context) { return getSharedPreferences(context, getDefaultSharedPreferencesName(context)); } private static String getDefaultSharedPreferencesName(Context context) { return context.getPackageName() + "_preferences"; } private static int getDefaultSharedPreferencesMode() { return Context.MODE_PRIVATE; } }