android.content.SharedPreferences

Here are the examples of the java api android.content.SharedPreferences taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11372 Examples 7

19 Source : SettingsFragment.java
with GNU General Public License v3.0
from zzzmobile

/**
 * Created by Usman Jamil on 4/18/2017.
 */
public clreplaced SettingsFragment extends PreferenceFragment implements iConstants {

    Preference path;

    int REQUEST_DIRECTORY = 123;

    private String mBaseFolderPath;

    SharedPreferences preferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        path = (Preference) findPreference("path");
        preferences = getActivity().getSharedPreferences(PREF_APPNAME, Context.MODE_PRIVATE);
        String folderName = DOWNLOAD_DIRECTORY;
        if (!preferences.getString("path", "DEFAULT").equals("DEFAULT")) {
            mBaseFolderPath = preferences.getString("path", "DEFAULT");
        } else {
            mBaseFolderPath = android.os.Environment.getExternalStorageDirectory() + File.separator + folderName;
        }
        path.setSummary(mBaseFolderPath);
        path.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            public boolean onPreferenceClick(Preference preference) {
                ChooseDirectoryDialog dialog = // Context
                ChooseDirectoryDialog.builder(getActivity()).replacedleText(// The replacedle will be shown
                "Choose directory").startDir(// File from where to start
                Environment.getExternalStorageDirectory().getAbsoluteFile()).showNeverAskAgain(// Enable or disable 'Never ask again checkbox
                false).neverAskAgainText(// Text of never ask again check box(if enabled)
                "Never ask again").onPickListener(new ChooseDirectoryDialog.DirectoryChooseListener() {

                    @Override
                    public void onDirectoryPicked(ChooseDirectoryDialog.DialogResult result) {
                        // Listener to users choice
                        // result.getPath() - The path of the folder picked by user
                        // result.isAskAgain()  - Did the user checked the 'Never ask again' Checkbox if true it means never ask again
                        // resultTV.setText("You picked \n " +
                        // result.getPath() +
                        // "\n Never ask again = " +
                        // result.isAskAgain());
                        path.setSummary(result.getPath());
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("path", result.getPath()).commit();
                    // new File(result.getPath())
                    }

                    @Override
                    public void onCancel() {
                    // resultTV.setText("operation canceled");
                    }
                }).build();
                dialog.show();
                return true;
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

19 Source : DataHelper.java
with Apache License 2.0
from Zweihui

/**
 * ================================================
 * 处理数据或本地文件的工具类
 * <p>
 * Created by JessYan on 2016/3/15
 * <a href="mailto:[email protected]">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public clreplaced DataHelper {

    private static SharedPreferences mSharedPreferences;

    public static final String SP_NAME = "config";

    private DataHelper() {
        throw new IllegalStateException("you can't instantiate me!");
    }

    /**
     * 存储重要信息到sharedPreferences;
     *
     * @param key
     * @param value
     */
    public static void setStringSF(Context context, String key, String value) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        mSharedPreferences.edit().putString(key, value).apply();
    }

    /**
     * 返回存在sharedPreferences的信息
     *
     * @param key
     * @return
     */
    public static String getStringSF(Context context, String key) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        return mSharedPreferences.getString(key, null);
    }

    /**
     * 存储重要信息到sharedPreferences;
     *
     * @param key
     * @param value
     */
    public static void setIntergerSF(Context context, String key, int value) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        mSharedPreferences.edit().putInt(key, value).apply();
    }

    /**
     * 返回存在sharedPreferences的信息
     *
     * @param key
     * @return
     */
    public static int getIntergerSF(Context context, String key) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        return mSharedPreferences.getInt(key, -1);
    }

    /**
     * 清除某个内容
     */
    public static void removeSF(Context context, String key) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        mSharedPreferences.edit().remove(key).apply();
    }

    /**
     * 使用递归查找是否存在文件
     *
     * @param dir
     * @return
     */
    public static boolean findFile(File dir) {
        if (dir == null) {
            return false;
        }
        if (!dir.isDirectory()) {
            return true;
        }
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                return true;
            } else if (file.isDirectory()) {
                // 递归调用继续删除
                findFile(file);
            }
        }
        return false;
    }

    /**
     * 清除Shareprefrence
     */
    public static void clearShareprefrence(Context context) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        mSharedPreferences.edit().clear().apply();
    }

    /**
     * 将对象储存到sharepreference
     *
     * @param key
     * @param device
     * @param <T>
     */
    public static <T> boolean saveDeviceData(Context context, String key, T device) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // Device为自定义类
            // 创建对象输出流,并封装字节流
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 将对象写入字节流
            oos.writeObject(device);
            // 将字节流编码成base64的字符串
            String oAuth_Base64 = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            mSharedPreferences.edit().putString(key, oAuth_Base64).apply();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将对象从shareprerence中取出来
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T getDeviceData(Context context, String key) {
        if (mSharedPreferences == null) {
            mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        T device = null;
        String productBase64 = mSharedPreferences.getString(key, null);
        if (productBase64 == null) {
            return null;
        }
        // 读取字节
        byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);
        // 封装到字节流
        ByteArrayInputStream bais = new ByteArrayInputStream(base64);
        try {
            // 再次封装
            ObjectInputStream bis = new ObjectInputStream(bais);
            // 读取对象
            device = (T) bis.readObject();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return device;
    }

    /**
     * 返回缓存文件夹
     */
    public static File getCacheFile(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = null;
            // 获取系统管理的sd卡缓存文件
            file = context.getExternalCacheDir();
            if (file == null) {
                // 如果获取的文件为空,就使用自己定义的缓存文件夹做缓存路径
                file = new File(getCacheFilePath(context));
                makeDirs(file);
            }
            return file;
        } else {
            return context.getCacheDir();
        }
    }

    /**
     * 获取自定义缓存文件地址
     *
     * @param context
     * @return
     */
    public static String getCacheFilePath(Context context) {
        String packageName = context.getPackageName();
        return "/mnt/sdcard/" + packageName;
    }

    /**
     * 创建未存在的文件夹
     *
     * @param file
     * @return
     */
    public static File makeDirs(File file) {
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 使用递归获取目录文件大小
     *
     * @param dir
     * @return
     */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                // 递归调用继续统计
                dirSize += getDirSize(file);
            }
        }
        return dirSize;
    }

    /**
     * 使用递归删除文件夹
     *
     * @param dir
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir == null) {
            return false;
        }
        if (!dir.isDirectory()) {
            return false;
        }
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                // 递归调用继续删除
                deleteDir(file);
            }
        }
        return true;
    }

    public static String bytyToString(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int num = 0;
        while ((num = in.read(buf)) != -1) {
            out.write(buf, 0, buf.length);
        }
        String result = out.toString();
        out.close();
        return result;
    }
}

19 Source : UserSeting.java
with Apache License 2.0
from zqljintu

public clreplaced UserSeting extends Application implements UserSetingImp {

    public SharedPreferences sharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        initSharedPreference();
    }

    private void initSharedPreference() {
        sharedPreferences = getSharedPreferences("config_jinnang", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
    }

    @Override
    public String getpreplacedswordfromSeting() {
        return sharedPreferences.getString("preplacedword", "null").toString();
    }

    @Override
    public String getquestionfromSeting() {
        return sharedPreferences.getString("question", "null").toString();
    }

    @Override
    public void putpreplacedwordonSeting(String preplacedword) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("preplacedword", preplacedword);
        editor.commit();
        editor.apply();
    }

    @Override
    public void putquestiononSeting(String question) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("question", question);
        editor.commit();
    }

    @Override
    public boolean iscurrentthePreplacedword(String preplacedword) {
        if (preplacedword.equals(this.getpreplacedswordfromSeting())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean iscurrentthQuestion(String qusetion) {
        if (qusetion.equals(this.getquestionfromSeting())) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isnullthepreplacedword() {
        if (this.getpreplacedswordfromSeting().equals("null")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isnullthequestion() {
        if (this.getquestionfromSeting().equals("null")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void putcurrentColor(int color) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("color", color);
        editor.commit();
    }

    @Override
    public List<Integer> getcurrentColor() {
        List<Integer> mlist = new ArrayList<>();
        switch(sharedPreferences.getInt("color", 0)) {
            case 0:
                mlist.add(0, getResources().getColor(R.color.colorFloatingButton));
                mlist.add(1, getResources().getColor(R.color.colorfirst));
                break;
            case 1:
                mlist.add(0, getResources().getColor(R.color.colorFloatingButton1));
                mlist.add(1, getResources().getColor(R.color.colorfirsr_1));
                break;
            case 2:
                mlist.add(0, getResources().getColor(R.color.colorFloatingButton2));
                mlist.add(1, getResources().getColor(R.color.colorfirst_2));
                break;
            case 3:
                mlist.add(0, getResources().getColor(R.color.colorFloatingButton3));
                mlist.add(1, getResources().getColor(R.color.colorfirst_3));
                break;
            case 4:
                mlist.add(0, getResources().getColor(R.color.colorFloatingButton4));
                mlist.add(1, getResources().getColor(R.color.colorfirst_4));
                break;
            default:
                break;
        }
        return mlist;
    }

    @Override
    public int getcurrentColorNum() {
        return sharedPreferences.getInt("color", 0);
    }
}

19 Source : UserSeting.java
with Apache License 2.0
from zqljintu

public clreplaced UserSeting extends Application implements UserSetingImp {

    private SharedPreferences sharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        initSharedPreferences();
    }

    private void initSharedPreferences() {
        sharedPreferences = getSharedPreferences("seting_ji", MODE_PRIVATE);
    }

    @Override
    public InterfaceState getInterfaceState() {
        InterfaceState interfaceState = new InterfaceState();
        if (sharedPreferences.getBoolean("night", false)) {
            interfaceState.setBackgroundcolor(getResources().getColor(R.color.colorNightmain));
            interfaceState.sereplacedemcolor(getResources().getColor(R.color.colorNighreplacedem));
            interfaceState.setTextcolor(getResources().getColor(R.color.colorNightText));
            interfaceState.setPagecolor(getResources().getColor(R.color.colorNighreplacedem));
            interfaceState.setNight(true);
        } else {
            interfaceState.setBackgroundcolor(getResources().getColor(R.color.colorDaymain));
            interfaceState.sereplacedemcolor(getResources().getColor(R.color.colorDayItem));
            interfaceState.setTextcolor(getResources().getColor(R.color.colorDatText));
            interfaceState.setPagecolor(getResources().getColor(R.color.color_feng));
            interfaceState.setNight(false);
        }
        return interfaceState;
    }

    @Override
    public void putNightState(boolean night) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("night", night);
        editor.commit();
        editor.apply();
    }

    @Override
    public boolean getNightState() {
        return sharedPreferences.getBoolean("night", false);
    }
}

19 Source : Plugin.java
with GNU General Public License v2.0
from ZorinOS

/**
 * Called when it's time to move the plugin settings from the global preferences
 * to device specific preferences
 *
 * @param globalSharedPreferences The global Preferences to copy the settings from
 */
public void copyGlobalToDeviceSpecificSettings(SharedPreferences globalSharedPreferences) {
}

19 Source : Plugin.java
with GNU General Public License v2.0
from ZorinOS

/**
 *  Called when the plugin should remove it's settings from the provided ShardPreferences
 *
 * @param sharedPreferences The SharedPreferences to remove the settings from
 */
public void removeSettings(SharedPreferences sharedPreferences) {
}

19 Source : FindMyPhoneSettingsFragment.java
with GNU General Public License v2.0
from ZorinOS

public clreplaced FindMyPhoneSettingsFragment extends PluginSettingsFragment {

    private static final int REQUEST_CODE_SELECT_RINGTONE = 1000;

    private String preferenceKeyRingtone;

    private SharedPreferences sharedPreferences;

    private Preference ringtonePreference;

    public static FindMyPhoneSettingsFragment newInstance(@NonNull String pluginKey) {
        FindMyPhoneSettingsFragment fragment = new FindMyPhoneSettingsFragment();
        fragment.setArguments(pluginKey);
        return fragment;
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        super.onCreatePreferences(savedInstanceState, rootKey);
        preferenceKeyRingtone = getString(R.string.findmyphone_preference_key_ringtone);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext());
        ringtonePreference = getPreferenceScreen().findPreference(preferenceKeyRingtone);
        setRingtoneSummary();
    }

    private void setRingtoneSummary() {
        String ringtone = sharedPreferences.getString(preferenceKeyRingtone, Settings.System.DEFAULT_RINGTONE_URI.toString());
        Uri ringtoneUri = Uri.parse(ringtone);
        ringtonePreference.setSummary(RingtoneManager.getRingtone(requireContext(), ringtoneUri).getreplacedle(requireContext()));
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        /*
         * There is no RingtonePreference in support library nor androidx, this is the workaround proposed here:
         * https://issuetracker.google.com/issues/37057453
         */
        if (preference.hasKey() && preference.getKey().equals(preferenceKeyRingtone)) {
            Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, Settings.System.DEFAULT_NOTIFICATION_URI);
            String existingValue = sharedPreferences.getString(preferenceKeyRingtone, null);
            if (existingValue != null) {
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(existingValue));
            } else {
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Settings.System.DEFAULT_RINGTONE_URI);
            }
            startActivityForResult(intent, REQUEST_CODE_SELECT_RINGTONE);
            return true;
        }
        return super.onPreferenceTreeClick(preference);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_SELECT_RINGTONE && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            if (uri != null) {
                sharedPreferences.edit().putString(preferenceKeyRingtone, uri.toString()).apply();
                setRingtoneSummary();
            }
        }
    }
}

19 Source : Prefs.java
with GNU Affero General Public License v3.0
from zood

public clreplaced Prefs {

    private static volatile Prefs sPrefs;

    private final SharedPreferences mPrefs;

    private final static String KEY_SECRET_KEY = "key_secret_key";

    private final static String KEY_PUBLIC_KEY = "key_public_key";

    private final static String KEY_PreplacedWORD_SALT = "key_preplacedword_salt";

    private final static String KEY_SYMMETRIC_KEY = "key_symmetric_key";

    private final static String KEY_ACCESS_TOKEN = "key_access_token";

    private final static String KEY_USER_ID = "key_user_id";

    private final static String KEY_FCM_TOKEN = "fcm_token";

    private final static String KEY_USERNAME = "key_username";

    private final static String KEY_CAMERA_POSITION_SAVED = "camera_position_saved";

    private final static String KEY_CAMERA_POSITION_LAreplacedUDE = "camera_position_lareplacedude";

    private final static String KEY_CAMERA_POSITION_LONGITUDE = "camera_position_longitude";

    private final static String KEY_CAMERA_POSITION_BEARING = "camera_position_bearing";

    private final static String KEY_CAMERA_POSITION_TILT = "camera_position_tilt";

    private final static String KEY_CAMERA_POSITION_ZOOM = "camera_position_zoom";

    private final static String KEY_LAST_LOCATION_UPDATE_TIME = "last_location_update_time";

    private final static String KEY_CURRENT_MOVEMENT = "current_movement";

    private final static String KEY_DEVICE_ID = "device_id";

    private final static String KEY_SHOWN_ONBOARDING = "shown_onboarding";

    private Prefs(Context context) {
        mPrefs = context.getSharedPreferences("secrets", Context.MODE_PRIVATE);
    }

    @NonNull
    public static Prefs get(@NonNull Context context) {
        if (sPrefs == null) {
            synchronized (Prefs.clreplaced) {
                if (sPrefs == null) {
                    sPrefs = new Prefs(context);
                }
            }
        }
        return sPrefs;
    }

    @AnyThread
    void clearAll() {
        mPrefs.edit().clear().apply();
    }

    @Nullable
    private byte[] getBytes(String key) {
        String hex = mPrefs.getString(key, null);
        if (hex == null) {
            return null;
        }
        return Hex.toBytes(hex);
    }

    private void setBytes(byte[] bytes, String key) {
        if (bytes != null) {
            String hex = Hex.toHexString(bytes);
            mPrefs.edit().putString(key, hex).apply();
        } else {
            mPrefs.edit().putString(key, null).apply();
        }
    }

    @Nullable
    public KeyPair getKeyPair() {
        byte[] secKey, pubKey;
        secKey = getBytes(KEY_SECRET_KEY);
        pubKey = getBytes(KEY_PUBLIC_KEY);
        if (secKey == null || pubKey == null) {
            return null;
        }
        KeyPair kp = new KeyPair();
        kp.secretKey = secKey;
        kp.publicKey = pubKey;
        return kp;
    }

    void setKeyPair(KeyPair kp) {
        if (kp != null) {
            setBytes(kp.secretKey, KEY_SECRET_KEY);
            setBytes(kp.publicKey, KEY_PUBLIC_KEY);
        } else {
            setBytes(null, KEY_SECRET_KEY);
            setBytes(null, KEY_PUBLIC_KEY);
        }
    }

    @Nullable
    byte[] getPreplacedwordSalt() {
        return getBytes(KEY_PreplacedWORD_SALT);
    }

    void setPreplacedwordSalt(byte[] salt) {
        setBytes(salt, KEY_PreplacedWORD_SALT);
    }

    @Nullable
    public byte[] getSymmetricKey() {
        return getBytes(KEY_SYMMETRIC_KEY);
    }

    void setSymmetricKey(byte[] symKey) {
        setBytes(symKey, KEY_SYMMETRIC_KEY);
    }

    @Nullable
    public String getAccessToken() {
        return mPrefs.getString(KEY_ACCESS_TOKEN, null);
    }

    public void setAccessToken(@Nullable String token) {
        if (TextUtils.isEmpty(token)) {
            // so we never have to deal with checking for empty strings anywhere else in the app
            token = null;
        }
        mPrefs.edit().putString(KEY_ACCESS_TOKEN, token).apply();
    }

    @Nullable
    public byte[] getUserId() {
        return getBytes(KEY_USER_ID);
    }

    public void setUserId(byte[] id) {
        setBytes(id, KEY_USER_ID);
    }

    public String getUsername() {
        return mPrefs.getString(KEY_USERNAME, null);
    }

    public void setUsername(String username) {
        mPrefs.edit().putString(KEY_USERNAME, username).apply();
    }

    @Nullable
    public String getFcmToken() {
        return mPrefs.getString(KEY_FCM_TOKEN, null);
    }

    public void setFcmToken(String token) {
        mPrefs.edit().putString(KEY_FCM_TOKEN, token).apply();
    }

    @Nullable
    public CameraPosition getCameraPosition() {
        if (!mPrefs.getBoolean(KEY_CAMERA_POSITION_SAVED, false)) {
            return null;
        }
        float bearing = 0;
        try {
            bearing = mPrefs.getFloat(KEY_CAMERA_POSITION_BEARING, 0);
        } catch (Throwable ignore) {
        }
        float tilt = 0;
        try {
            tilt = mPrefs.getFloat(KEY_CAMERA_POSITION_TILT, 0);
        } catch (Throwable ignore) {
        }
        float zoom = 0;
        try {
            zoom = mPrefs.getFloat(KEY_CAMERA_POSITION_ZOOM, 0);
        } catch (Throwable ignore) {
        }
        double lat = Double.longBitsToDouble(mPrefs.getLong(KEY_CAMERA_POSITION_LAreplacedUDE, 0));
        double lng = Double.longBitsToDouble(mPrefs.getLong(KEY_CAMERA_POSITION_LONGITUDE, 0));
        LatLng ll = new LatLng(lat, lng);
        return new CameraPosition.Builder().bearing(bearing).target(ll).tilt(tilt).zoom(zoom).build();
    }

    public void setCameraPosition(@Nullable CameraPosition pos) {
        if (pos == null) {
            mPrefs.edit().putBoolean(KEY_CAMERA_POSITION_SAVED, false).apply();
            return;
        }
        mPrefs.edit().putFloat(KEY_CAMERA_POSITION_BEARING, pos.bearing).putFloat(KEY_CAMERA_POSITION_TILT, pos.tilt).putFloat(KEY_CAMERA_POSITION_ZOOM, pos.zoom).putLong(KEY_CAMERA_POSITION_LAreplacedUDE, Double.doubleToRawLongBits(pos.target.lareplacedude)).putLong(KEY_CAMERA_POSITION_LONGITUDE, Double.doubleToRawLongBits(pos.target.longitude)).putBoolean(KEY_CAMERA_POSITION_SAVED, true).apply();
    }

    public long getLastLocationUpdateTime() {
        return mPrefs.getLong(KEY_LAST_LOCATION_UPDATE_TIME, 0);
    }

    void setLastLocationUpdateTime(long time) {
        mPrefs.edit().putLong(KEY_LAST_LOCATION_UPDATE_TIME, time).apply();
    }

    @NonNull
    public MovementType getCurrentMovement() {
        return MovementType.get(mPrefs.getString(KEY_CURRENT_MOVEMENT, null));
    }

    public void setCurrentMovement(@NonNull MovementType mvmt) {
        mPrefs.edit().putString(KEY_CURRENT_MOVEMENT, mvmt.val).apply();
    }

    @NonNull
    @CheckResult
    @Size(Constants.DEVICE_ID_SIZE)
    byte[] getDeviceId() {
        byte[] deviceId = getBytes(KEY_DEVICE_ID);
        if (deviceId == null) {
            deviceId = new byte[Constants.DEVICE_ID_SIZE];
            new SecureRandom().nextBytes(deviceId);
            setBytes(deviceId, KEY_DEVICE_ID);
        }
        return deviceId;
    }

    public boolean getShownOnboarding() {
        return mPrefs.getBoolean(KEY_SHOWN_ONBOARDING, false);
    }

    public void setShownOnboarding() {
        mPrefs.edit().putBoolean(KEY_SHOWN_ONBOARDING, true).apply();
    }
}

19 Source : LaunchAppViaDialReceiver.java
with BSD 2-Clause "Simplified" License
from zolamk

public clreplaced LaunchAppViaDialReceiver extends BroadcastReceiver {

    SharedPreferences appSettings;

    @Override
    public void onReceive(Context context, Intent intent) {
        appSettings = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
        String numberToDial = appSettings.getString("numberToDial", "111");
        String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        if (phoneNumber.equals(numberToDial)) {
            setResultData(null);
            Intent appIntent = new Intent(context, ScheduleCallActivity.clreplaced);
            appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(appIntent);
        }
    }
}

19 Source : PersistentCookieStore.java
with Apache License 2.0
from zion223

/**
 * <pre>
 *     OkHttpClient client = new OkHttpClient.Builder()
 *             .cookieJar(new JavaNetCookieJar(new CookieManager(
 *                     new PersistentCookieStore(getApplicationContext()),
 *                             CookiePolicy.ACCEPT_ALL))
 *             .build();
 *
 * </pre>
 * <p/>
 * from
 * http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-
 * okhttp-2-on-android
 * <p/>
 * <br/>
 * A persistent cookie store which implements the Apache HttpClient CookieStore
 * interface. Cookies are stored and will persist on the user's device between
 * application sessions since they are serialized and stored in
 * SharedPreferences. Instances of this clreplaced are designed to be used with
 * AsyncHttpClient#setCookieStore, but can also be used with a regular old
 * apache HttpClient/HttpContext if you prefer.
 */
public clreplaced PersistentCookieStore implements CookieStore {

    private static final String LOG_TAG = "PersistentCookieStore";

    private static final String COOKIE_PREFS = "CookiePrefsFile";

    private static final String COOKIE_NAME_PREFIX = "cookie_";

    private final HashMap<String, ConcurrentHashMap<String, HttpCookie>> cookies;

    private final SharedPreferences cookiePrefs;

    /**
     * Construct a persistent cookie store.
     *
     * @param context
     *            Context to attach cookie store to
     */
    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<String, ConcurrentHashMap<String, HttpCookie>>();
        // Load any previously stored cookies into the store
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) {
                String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
                for (String name : cookieNames) {
                    String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
                    if (encodedCookie != null) {
                        HttpCookie decodedCookie = decodeCookie(encodedCookie);
                        if (decodedCookie != null) {
                            if (!cookies.containsKey(entry.getKey()))
                                cookies.put(entry.getKey(), new ConcurrentHashMap<String, HttpCookie>());
                            cookies.get(entry.getKey()).put(name, decodedCookie);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void add(URI uri, HttpCookie cookie) {
        String name = getCookieToken(uri, cookie);
        // Save cookie into local store, or remove if expired
        if (!cookie.hasExpired()) {
            if (!cookies.containsKey(uri.getHost()))
                cookies.put(uri.getHost(), new ConcurrentHashMap<String, HttpCookie>());
            cookies.get(uri.getHost()).put(name, cookie);
        } else {
            if (cookies.containsKey(uri.toString()))
                cookies.get(uri.getHost()).remove(name);
        }
        // Save cookie into persistent store
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
        prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie)));
        prefsWriter.commit();
    }

    protected String getCookieToken(URI uri, HttpCookie cookie) {
        return cookie.getName() + cookie.getDomain();
    }

    @Override
    public List<HttpCookie> get(URI uri) {
        ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
        if (cookies.containsKey(uri.getHost()))
            ret.addAll(cookies.get(uri.getHost()).values());
        return ret;
    }

    @Override
    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.commit();
        cookies.clear();
        return true;
    }

    @Override
    public boolean remove(URI uri, HttpCookie cookie) {
        String name = getCookieToken(uri, cookie);
        if (cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name)) {
            cookies.get(uri.getHost()).remove(name);
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
                prefsWriter.remove(COOKIE_NAME_PREFIX + name);
            }
            prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
            prefsWriter.commit();
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<HttpCookie> getCookies() {
        ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
        for (String key : cookies.keySet()) ret.addAll(cookies.get(key).values());
        return ret;
    }

    @Override
    public List<URI> getURIs() {
        ArrayList<URI> ret = new ArrayList<URI>();
        for (String key : cookies.keySet()) try {
            ret.add(new URI(key));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * Serializes Cookie object into String
     *
     * @param cookie
     *            cookie to be encoded, can be null
     * @return cookie encoded as String
     */
    protected String encodeCookie(SerializableHttpCookie cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in encodeCookie", e);
            return null;
        }
        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * Returns cookie decoded from cookie string
     *
     * @param cookieString
     *            string of cookie as returned from http request
     * @return decoded cookie or null if exception occured
     */
    protected HttpCookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        HttpCookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in decodeCookie", e);
        } catch (ClreplacedNotFoundException e) {
            Log.d(LOG_TAG, "ClreplacedNotFoundException in decodeCookie", e);
        }
        return cookie;
    }

    /**
     * Using some super basic byte array <-> hex conversions so we don't
     * have to rely on any large Base64 libraries. Can be overridden if you
     * like!
     *
     * @param bytes
     *            byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * Converts hex values from strings to byte arra
     *
     * @param hexString
     *            string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}

19 Source : SharePreferenceUtil.java
with Apache License 2.0
from zion223

/**
 * 本地SharePreference工具
 */
public clreplaced SharePreferenceUtil {

    private static final String TAG = "SharePreferenceUtil";

    private static SharedPreferences sp;

    private static SharedPreferences.Editor editor;

    private static SharePreferenceUtil mInstance;

    private Locale systemCurrentLocal = Locale.CHINESE;

    private SharePreferenceUtil() {
    }

    @SuppressLint("CommitPrefEdits")
    private static void init(Context context) {
        if (sp == null) {
            sp = context.getSharedPreferences(Constants.SHARED_PREFERENCE_FILE_NAME, Context.MODE_PRIVATE);
        }
        editor = sp.edit();
    }

    public static SharePreferenceUtil getInstance(Context context) {
        if (mInstance == null) {
            synchronized (SharePreferenceUtil.clreplaced) {
                if (mInstance == null) {
                    init(context);
                    mInstance = new SharePreferenceUtil();
                }
            }
        }
        return mInstance;
    }

    int getSelectLanguage() {
        return getInt(Constants.SpKey.TAG_LANGUAGE, 0);
    }

    Locale getSystemCurrentLocal() {
        return systemCurrentLocal;
    }

    public int getLocalMusicCount() {
        return Integer.parseInt(getString(LOCAL_MUSIC_COUNT, "0"));
    }

    public void saveLocalMusicCount(int count) {
        saveString(LOCAL_MUSIC_COUNT, String.valueOf(count));
    }

    /**
     * 保存用户的信息以及电话号码(因为bean里的电话号码要处理字符串,所以这里直接暴力传比较高效)
     *
     * @param bean
     */
    public void saveUserInfo(LoginBean bean, String phoneNumber) {
        if (bean.getBindings().size() > 1) {
            saveAuthToken(bean.getBindings().get(1).getTokenJsonStr());
        }
        saveUserId(String.valueOf(bean.getProfile().getUserId()));
        saveAccountNum(phoneNumber);
        saveString(Constants.SpKey.USER_INFO, GsonUtil.toJson(bean));
    }

    public String getUserInfo(String defaultValue) {
        return getString(Constants.SpKey.USER_INFO, defaultValue);
    }

    private void saveAccountNum(String phoneNumber) {
        saveString(Constants.SpKey.PHONE_NUMBER, phoneNumber);
    }

    private void saveUserId(String id) {
        saveString(Constants.SpKey.USER_ID, id);
    }

    private void getUserId(String id) {
        getString(Constants.SpKey.USER_ID, id);
    }

    public String getAccountNum() {
        return getString(Constants.SpKey.PHONE_NUMBER, "");
    }

    private void saveAuthToken(String token) {
        saveString(Constants.SpKey.AUTH_TOKEN, token);
    }

    /**
     * 获取AuthToken
     */
    public String getAuthToken(String defaultValue) {
        return getString(Constants.SpKey.AUTH_TOKEN, defaultValue);
    }

    /*
     * 存储最近一次听过的歌曲
     */
    // public void saveLatestSong(SongInfo songInfo) {
    // String song = GsonUtil.toJson(songInfo);
    // saveString(Constants.SpKey.LATEST_SONG, song);
    // }
    // 
    // public SongInfo getLatestSong() {
    // return GsonUtil.fromJSON(getString(Constants.SpKey.LATEST_SONG, ""), SongInfo.clreplaced);
    // }
    /**
     * 保存上次获取日推的时间
     */
    public void saveDailyUpdateTime(long updateTime) {
        saveLong(Constants.SpKey.DAILY_UPDATE_TIME, updateTime);
    }

    /**
     * 存储当前歌手ID
     */
    public void saveCurrentArtistId(String id) {
        saveString(Constants.SpKey.CURRENT_ARTIST_ID, id);
    }

    public void removeCurrentArtistId() {
        remove(Constants.SpKey.CURRENT_ARTIST_ID);
    }

    public String getCurrentArtistId() {
        return getString(Constants.SpKey.CURRENT_ARTIST_ID, "");
    }

    public long getDailyUpdateTime() {
        return getLong(Constants.SpKey.DAILY_UPDATE_TIME, 0);
    }

    /**
     * 保存喜欢的歌曲列表
     */
    public void saveLikeList(List<String> likeList) {
        String likeListString = GsonUtil.toJson(likeList);
        saveString(Constants.SpKey.LIKE_LIST, likeListString);
    }

    public List<String> getLikeList() {
        String likeListString = getString(Constants.SpKey.LIKE_LIST, "");
        return GsonUtil.fromJSON(likeListString, List.clreplaced);
    }

    public void remove(String key) {
        editor.remove(key).apply();
    }

    private String getString(String key, String defaultValue) {
        return sp.getString(key, defaultValue);
    }

    private void saveLong(String key, long values) {
        editor.putLong(key, values);
    }

    private long getLong(String key, long defaultValue) {
        return sp.getLong(key, defaultValue);
    }

    private int getInt(String key, int defaultValue) {
        return sp.getInt(key, defaultValue);
    }

    private void saveString(String key, String value) {
        editor.putString(key, value).apply();
    }
}

19 Source : PreferencesUtil.java
with Apache License 2.0
from zion223

public final clreplaced PreferencesUtil {

    public static final String ARTIST_SORT_ORDER = "artist_sort_order";

    public static final String ARTIST_SONG_SORT_ORDER = "artist_song_sort_order";

    public static final String ARTIST_ALBUM_SORT_ORDER = "artist_album_sort_order";

    public static final String ALBUM_SORT_ORDER = "album_sort_order";

    public static final String ALBUM_SONG_SORT_ORDER = "album_song_sort_order";

    public static final String SONG_SORT_ORDER = "song_sort_order";

    private static final String NOW_PLAYING_SELECTOR = "now_paying_selector";

    private static final String TOGGLE_ANIMATIONS = "toggle_animations";

    private static final String TOGGLE_SYSTEM_ANIMATIONS = "toggle_system_animations";

    private static final String TOGGLE_ARTIST_GRID = "toggle_artist_grid";

    private static final String TOGGLE_ALBUM_GRID = "toggle_album_grid";

    private static final String TOGGLE_HEADPHONE_PAUSE = "toggle_headphone_pause";

    private static final String THEME_PREFERNCE = "theme_preference";

    private static final String START_PAGE_INDEX = "start_page_index";

    private static final String START_PAGE_PREFERENCE_LASTOPENED = "start_page_preference_latopened";

    private static final String NOW_PLAYNG_THEME_VALUE = "now_playing_theme_value";

    private static final String FAVRIATE_MUSIC_PLAYLIST = "favirate_music_playlist";

    private static final String DOWNMUSIC_BIT = "down_music_bit";

    private static final String CURRENT_DATE = "currentdate";

    private static PreferencesUtil sInstance;

    private static SharedPreferences mPreferences;

    public PreferencesUtil(final Context context) {
        mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static final PreferencesUtil getInstance(final Context context) {
        if (sInstance == null) {
            sInstance = new PreferencesUtil(context.getApplicationContext());
        }
        return sInstance;
    }

    public long lastExit() {
        return mPreferences.getLong("last_err_exit", 0);
    }

    public void setExitTime() {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putLong("last_err_exit", System.currentTimeMillis());
        editor.commit();
    }

    public boolean isCurrentDayFirst(String str) {
        return mPreferences.getString(CURRENT_DATE, "").equals(str);
    }

    public void setCurrentDate(String str) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString(CURRENT_DATE, str);
        editor.apply();
    }

    public void setPlayLink(long id, String link) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString(id + "", link);
        editor.apply();
    }

    public String getPlayLink(long id) {
        return mPreferences.getString(id + "", null);
    }

    public void sereplacedemPostion(String str) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString("item_relative_position", str);
        editor.apply();
    }

    public String gereplacedemPosition() {
        return mPreferences.getString("item_relative_position", "推荐歌单 最新专辑 主播电台");
    }

    public void setDownMusicBit(int bit) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putInt(DOWNMUSIC_BIT, bit);
        editor.apply();
    }

    public int getDownMusicBit() {
        return mPreferences.getInt(DOWNMUSIC_BIT, 192);
    }

    public boolean getFavriateMusicPlaylist() {
        return mPreferences.getBoolean(FAVRIATE_MUSIC_PLAYLIST, false);
    }

    public void setFavriateMusicPlaylist(boolean b) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(FAVRIATE_MUSIC_PLAYLIST, b);
        editor.apply();
    }

    public void setOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        mPreferences.registerOnSharedPreferenceChangeListener(listener);
    }

    public boolean getAnimations() {
        return mPreferences.getBoolean(TOGGLE_ANIMATIONS, true);
    }

    public boolean getSystemAnimations() {
        return mPreferences.getBoolean(TOGGLE_SYSTEM_ANIMATIONS, true);
    }

    public boolean isArtistsInGrid() {
        return mPreferences.getBoolean(TOGGLE_ARTIST_GRID, true);
    }

    public void setArtistsInGrid(final boolean b) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(final Void... unused) {
                final SharedPreferences.Editor editor = mPreferences.edit();
                editor.putBoolean(TOGGLE_ARTIST_GRID, b);
                editor.apply();
                return null;
            }
        }.execute();
    }

    public boolean isAlbumsInGrid() {
        return mPreferences.getBoolean(TOGGLE_ALBUM_GRID, true);
    }

    public void setAlbumsInGrid(final boolean b) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(final Void... unused) {
                final SharedPreferences.Editor editor = mPreferences.edit();
                editor.putBoolean(TOGGLE_ALBUM_GRID, b);
                editor.apply();
                return null;
            }
        }.execute();
    }

    public boolean pauseEnabledOnDetach() {
        return mPreferences.getBoolean(TOGGLE_HEADPHONE_PAUSE, true);
    }

    public String getTheme() {
        return mPreferences.getString(THEME_PREFERNCE, "light");
    }

    public int getStartPageIndex() {
        return mPreferences.getInt(START_PAGE_INDEX, 0);
    }

    public void setStartPageIndex(final int index) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(final Void... unused) {
                final SharedPreferences.Editor editor = mPreferences.edit();
                editor.putInt(START_PAGE_INDEX, index);
                editor.apply();
                return null;
            }
        }.execute();
    }

    public void setLastOpenedreplacedtartPagePreference(boolean preference) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(START_PAGE_PREFERENCE_LASTOPENED, preference);
        editor.apply();
    }

    public boolean lastOpenedIsStartPagePreference() {
        return mPreferences.getBoolean(START_PAGE_PREFERENCE_LASTOPENED, true);
    }

    private void setSortOrder(final String key, final String value) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(final Void... unused) {
                final SharedPreferences.Editor editor = mPreferences.edit();
                editor.putString(key, value);
                editor.apply();
                return null;
            }
        }.execute();
    }

    public final String getArtistSortOrder() {
        return mPreferences.getString(ARTIST_SORT_ORDER, SortOrder.ArtistSortOrder.ARTIST_A_Z);
    }

    public void setArtistSortOrder(final String value) {
        setSortOrder(ARTIST_SORT_ORDER, value);
    }

    public final String getArtistSongSortOrder() {
        return mPreferences.getString(ARTIST_SONG_SORT_ORDER, SortOrder.ArtistSongSortOrder.SONG_A_Z);
    }

    public static String FOLDER_SONG_SORT_ORDER = "folder_sort";

    public void setFolerSortOrder(final String value) {
        setSortOrder(FOLDER_SONG_SORT_ORDER, value);
    }

    public final String getFoloerSortOrder() {
        return mPreferences.getString(FOLDER_SONG_SORT_ORDER, SortOrder.FolderSortOrder.FOLDER_A_Z);
    }

    public void setArtistSongSortOrder(final String value) {
        setSortOrder(ARTIST_SONG_SORT_ORDER, value);
    }

    public final String getArtistAlbumSortOrder() {
        return mPreferences.getString(ARTIST_ALBUM_SORT_ORDER, SortOrder.ArtistAlbumSortOrder.ALBUM_A_Z);
    }

    public void setArtistAlbumSortOrder(final String value) {
        setSortOrder(ARTIST_ALBUM_SORT_ORDER, value);
    }

    public final String getAlbumSortOrder() {
        return mPreferences.getString(ALBUM_SORT_ORDER, SortOrder.AlbumSortOrder.ALBUM_A_Z);
    }

    public void setAlbumSortOrder(final String value) {
        setSortOrder(ALBUM_SORT_ORDER, value);
    }

    public final String getAlbumSongSortOrder() {
        return mPreferences.getString(ALBUM_SONG_SORT_ORDER, SortOrder.AlbumSongSortOrder.SONG_TRACK_LIST);
    }

    public void setAlbumSongSortOrder(final String value) {
        setSortOrder(ALBUM_SONG_SORT_ORDER, value);
    }

    public final String getSongSortOrder() {
        return mPreferences.getString(SONG_SORT_ORDER, SortOrder.SongSortOrder.SONG_A_Z);
    }

    public void setSongSortOrder(final String value) {
        setSortOrder(SONG_SORT_ORDER, value);
    }

    public final boolean didNowplayingThemeChanged() {
        return mPreferences.getBoolean(NOW_PLAYNG_THEME_VALUE, false);
    }

    public void setNowPlayingThemeChanged(final boolean value) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(NOW_PLAYNG_THEME_VALUE, value);
        editor.apply();
    }

    public void setFilterSize(int size) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putInt("filtersize", size);
        editor.apply();
    }

    public void setFilterTime(int time) {
        final SharedPreferences.Editor editor = mPreferences.edit();
        editor.putInt("filtertime", time);
        editor.apply();
    }

    public int getFilterSize() {
        return mPreferences.getInt("filtersize", 1024 * 1024);
    }

    public int getFilterTime() {
        return mPreferences.getInt("filtertime", 60 * 1000);
    }
}

19 Source : LattePreference.java
with MIT License
from zion223

public final clreplaced LattePreference {

    /**
     * 提示:
     * Activity.getPreferences(int mode)生成 Activity名.xml 用于Activity内部存储
     * PreferenceManager.getDefaultSharedPreferences(Context)生成 包名_preferences.xml
     * Context.getSharedPreferences(String name,int mode)生成name.xml
     */
    private static final SharedPreferences PREFERENCES = PreferenceManager.getDefaultSharedPreferences(Latte.getApplication());

    private static final String APP_PREFERENCES_KEY = "profile";

    private static SharedPreferences getAppPreference() {
        return PREFERENCES;
    }

    public static void setAppProfile(String val) {
        getAppPreference().edit().putString(APP_PREFERENCES_KEY, val).apply();
    }

    public static String getAppProfile() {
        return getAppPreference().getString(APP_PREFERENCES_KEY, null);
    }

    public static JSONObject getAppProfileJson() {
        final String profile = getAppProfile();
        return JSON.parseObject(profile);
    }

    public static void removeAppProfile() {
        getAppPreference().edit().remove(APP_PREFERENCES_KEY).apply();
    }

    public static void clearAppPreferences() {
        getAppPreference().edit().clear().apply();
    }

    public static void setAppFlag(String key, boolean flag) {
        getAppPreference().edit().putBoolean(key, flag).apply();
    }

    public static boolean getAppFlag(String key) {
        return getAppPreference().getBoolean(key, false);
    }

    public static void addCustomAppProfile(String key, String val) {
        getAppPreference().edit().putString(key, val).apply();
    }

    public static String getCustomAppProfile(String key) {
        return getAppPreference().getString(key, "");
    }
}

19 Source : PersistentCookieStore.java
with Apache License 2.0
from zhou-you

/**
 * <p>描述:cookie存储器</p>
 * 作者: zhouyou<br>
 * 日期: 2016/12/19 16:35<br>
 * 版本: v2.0<br>
 */
public clreplaced PersistentCookieStore {

    private static final String COOKIE_PREFS = "Cookies_Prefs";

    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;

    private final SharedPreferences cookiePrefs;

    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<>();
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey())) {
                            cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
                        }
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }
        }
    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }

    /*public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);
        if (cookie.persistent()) {
            if (!cookies.containsKey(url.host())) {
                cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
            }
            cookies.get(url.host()).put(name, cookie);
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
            prefsWriter.apply();
        } else {
            if (cookies.containsKey(url.host())) {
                cookies.get(url.host()).remove(name);
            }
        }
    }*/
    public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);
        // 添加 host key. 否则有可能抛空.
        if (!cookies.containsKey(url.host())) {
            cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
        }
        // 删除已经有的.
        if (cookies.containsKey(url.host())) {
            cookies.get(url.host()).remove(name);
        }
        // 添加新的进去
        cookies.get(url.host()).put(name, cookie);
        // 是否保存到 SP 中
        if (cookie.persistent()) {
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
            prefsWriter.apply();
        } else {
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            prefsWriter.remove(url.host());
            prefsWriter.remove(name);
            prefsWriter.apply();
        }
    }

    public void addCookies(List<Cookie> cookies) {
        for (Cookie cookie : cookies) {
            String domain = cookie.domain();
            ConcurrentHashMap<String, Cookie> domainCookies = this.cookies.get(domain);
            if (domainCookies == null) {
                domainCookies = new ConcurrentHashMap<>();
                this.cookies.put(domain, domainCookies);
            }
        }
    }

    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());
        return ret;
    }

    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        cookies.clear();
        return true;
    }

    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);
        if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
            cookies.get(url.host()).remove(name);
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(name)) {
                prefsWriter.remove(name);
            }
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.apply();
            return true;
        } else {
            return false;
        }
    }

    public List<Cookie> getCookies() {
        ArrayList<Cookie> ret = new ArrayList<>();
        for (String key : cookies.keySet()) ret.addAll(cookies.get(key).values());
        return ret;
    }

    /**
     * cookies to string
     */
    protected String encodeCookie(SerializableOkHttpCookies cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
            HttpLog.d("IOException in encodeCookie" + e.getMessage());
            return null;
        }
        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * String to cookies
     */
    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
        } catch (IOException e) {
            HttpLog.d("IOException in decodeCookie" + e.getMessage());
        } catch (ClreplacedNotFoundException e) {
            HttpLog.d("ClreplacedNotFoundException in decodeCookie" + e.getMessage());
        }
        return cookie;
    }

    /**
     * byteArrayToHexString
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * hexStringToByteArray
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}

19 Source : SignatureConfigFragment.java
with GNU General Public License v3.0
from zhoorta

/**
 * A placeholder fragment containing a simple view.
 */
public clreplaced SignatureConfigFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    private PageViewModel pageViewModel;

    SharedPreferences config;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel.clreplaced);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
        pageViewModel.setIndex(index);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_signature_config, container, false);
        // 0 - for private mode
        config = this.getActivity().getSharedPreferences("SignerConfig", 0);
        Button button = root.findViewById(R.id.buttonSaveSignatureConfig);
        final EditText textXPos = root.findViewById(R.id.editXPos);
        final EditText textYPos = root.findViewById(R.id.editYPos);
        final EditText textWidth = root.findViewById(R.id.editWidth);
        final EditText textHeight = root.findViewById(R.id.editHeight);
        final EditText textPage = root.findViewById(R.id.editPage);
        textXPos.setText(config.getString("xpos", "110"));
        textYPos.setText(config.getString("ypos", "170"));
        textWidth.setText(config.getString("width", "200"));
        textHeight.setText(config.getString("height", "50"));
        textPage.setText(config.getString("page", "1"));
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                SharedPreferences.Editor editor = config.edit();
                editor.putString("xpos", textXPos.getText().toString());
                editor.putString("ypos", textYPos.getText().toString());
                editor.putString("width", textWidth.getText().toString());
                editor.putString("height", textHeight.getText().toString());
                editor.putString("page", textPage.getText().toString());
                editor.commit();
                Intent returnIntent = new Intent();
                getActivity().setResult(Activity.RESULT_OK, returnIntent);
                getActivity().finish();
            }
        });
        return root;
    }
}

19 Source : ServerConfigFragment.java
with GNU General Public License v3.0
from zhoorta

/**
 * A placeholder fragment containing a simple view.
 */
public clreplaced ServerConfigFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    private PageViewModel pageViewModel;

    SharedPreferences config;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel.clreplaced);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
        pageViewModel.setIndex(index);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_server_config, container, false);
        // 0 - for private mode
        config = this.getActivity().getSharedPreferences("SignerConfig", 0);
        Button button = root.findViewById(R.id.buttonConfig);
        final EditText textServer = root.findViewById(R.id.editServer);
        final EditText textUsername = root.findViewById(R.id.editUsername);
        final EditText textPreplacedword = root.findViewById(R.id.editPreplacedword);
        final EditText textDomain = root.findViewById(R.id.editDomain);
        final EditText textShare = root.findViewById(R.id.editShare);
        final EditText textSuffix = root.findViewById(R.id.editSuffix);
        textServer.setText(config.getString("server", null));
        textUsername.setText(config.getString("username", null));
        textPreplacedword.setText(config.getString("preplacedword", null));
        textDomain.setText(config.getString("domain", null));
        textShare.setText(config.getString("share", null));
        textSuffix.setText(config.getString("suffix", null));
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                String server = textServer.getText().toString();
                String username = textUsername.getText().toString();
                String preplacedword = textPreplacedword.getText().toString();
                String domain = textDomain.getText().toString();
                String share = textShare.getText().toString();
                String suffix = textSuffix.getText().toString();
                SharedPreferences.Editor editor = config.edit();
                editor.putString("server", server);
                editor.putString("username", username);
                editor.putString("preplacedword", preplacedword);
                editor.putString("domain", domain);
                editor.putString("share", share);
                editor.putString("suffix", suffix);
                editor.commit();
                Intent returnIntent = new Intent();
                getActivity().setResult(Activity.RESULT_OK, returnIntent);
                getActivity().finish();
            }
        });
        return root;
    }
}

19 Source : GetSignatureActivity.java
with GNU General Public License v3.0
from zhoorta

public clreplaced GetSignatureActivity extends AppCompatActivity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private SignaturePad mSignaturePad;

    private Button mClearButton;

    private Button mSaveButton;

    private SharedPreferences config;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_signature);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        config = getSharedPreferences("SignerConfig", 0);
        mSignaturePad = findViewById(R.id.signature_pad);
        mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {

            @Override
            public void onStartSigning() {
            // Toast.makeText(GetSignatureActivity.this, "OnStartSigning", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSigned() {
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
            }

            @Override
            public void onClear() {
                mSaveButton.setEnabled(false);
                mClearButton.setEnabled(false);
            }
        });
        mClearButton = findViewById(R.id.clear_button);
        mSaveButton = findViewById(R.id.save_button);
        mClearButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                mSignaturePad.clear();
            }
        });
        mSaveButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                alert(getResources().getString(R.string.info_saving_doreplacedent));
                new SMBServerConnect(new SMBServerConnect.AsyncResponse() {

                    @Override
                    public void processFinish(final SMBTools smb, String error) {
                        if (smb == null) {
                            alert(error);
                            return;
                        }
                        try {
                            int xpos = Integer.parseInt(config.getString("xpos", "110"));
                            int ypos = Integer.parseInt(config.getString("ypos", "170"));
                            int width = Integer.parseInt(config.getString("width", "200"));
                            int height = Integer.parseInt(config.getString("height", "50"));
                            int page = Integer.parseInt(config.getString("page", "1"));
                            PDFTools pdf = new PDFTools(getApplicationContext());
                            Bitmap signatureBitmap = mSignaturePad.getTransparentSignatureBitmap();
                            final File outputSignature = saveSignature(signatureBitmap);
                            final File tmpLocalFile = new File(getIntent().getExtras().getString("file"));
                            pdf.open(tmpLocalFile);
                            pdf.insertImage(outputSignature.getPath(), xpos, ypos, width, height, page);
                            new SMBCopyLocalFile(smb, GetSignatureActivity.this.config.getString("outboundPath", "out") + "\\" + getIntent().getExtras().getString("source"), new SMBCopyLocalFile.AsyncResponse() {

                                @Override
                                public void processFinish(boolean success, String error) {
                                    // tmpLocalFile.delete();
                                    outputSignature.delete();
                                    new SMBDeleteRemoteFile(smb, new SMBDeleteRemoteFile.AsyncResponse() {

                                        @Override
                                        public void processFinish(boolean success, String error) {
                                            smb.close();
                                            finish();
                                            Intent intent = new Intent(GetSignatureActivity.this, ShowFinalDoreplacedentActivity.clreplaced);
                                            intent.putExtra("file", tmpLocalFile.getAbsolutePath());
                                            startActivity(intent);
                                        }
                                    }).execute(GetSignatureActivity.this.config.getString("inboundPath", "in") + "\\" + getIntent().getExtras().getString("source"));
                                }
                            }).execute(tmpLocalFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).execute(getApplicationContext());
            }
        });
    }

    private void alert(String message) {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        // alertDialog.setreplacedle("Success");
        alertDialog.setMessage(message);
        alertDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // Toast.makeText(GetSignatureActivity.this, "Cannot write images to external storage", Toast.LENGTH_SHORT).show();
                    }
                }
        }
    }

    private void saveBitmapToPNG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        stream.close();
    }

    private File saveSignature(Bitmap signature) {
        try {
            File output = File.createTempFile("signer", ".png", getApplicationContext().getCacheDir());
            saveBitmapToPNG(signature, output);
            return output;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

19 Source : SPUtil.java
with Apache License 2.0
from zhonglikui

/**
 * Created by zhong on 2016/3/21.
 * 获取sd卡路径的工具类
 */
public clreplaced SPUtil {

    private static final String INVALID_STRING_VALUE = null;

    private static final int INVALID_INT_VALUE = -1;

    private static final float INVALID_FLOAT_VALUE = -1F;

    private static final long INVALID_LONG_VALUE = -1L;

    private static final boolean INVALID_BOOLEAN_VALUE = false;

    private static SharedPreferences sharedPreferences;

    // 进行数据加密的类
    private static Encrypt encrypt;

    private SPUtil() {
    }

    public static void init(String preplacedword) {
    // encrypt = new EncryptByPbe(preplacedword);
    }

    /**
     * @return 获取到的SharedPreferences实例
     */
    private static SharedPreferences getSharedPreferences() {
        if (sharedPreferences == null) {
            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getInstance().getContext());
        }
        return sharedPreferences;
    }

    /**
     * @param key   要保存的String类型数据的key
     * @param value String类型的value
     */
    public static void putString(String key, String value) {
        key = encodString(key);
        value = encodString(value);
        if (!TextUtils.isEmpty(value)) {
            getSharedPreferences().edit().putString(key, value).commit();
        }
    }

    /**
     * @param key 获取String类型数据的key
     * @return String类型的value
     */
    public static String getString(String key) {
        key = encodString(key);
        String value = getSharedPreferences().getString(key, INVALID_STRING_VALUE);
        if (TextUtils.isEmpty(value)) {
            return null;
        } else {
            return decodeString(value);
        }
    }

    /**
     * @param key   要保存的int类型数据的key
     * @param value int类型的value
     */
    public static void putInt(String key, int value) {
        key = encodString(key);
        getSharedPreferences().edit().putInt(key, value).commit();
    }

    /**
     * @param key 获取int类型数据的key
     * @return int类型的value
     */
    public static int getInt(String key) {
        key = encodString(key);
        return getSharedPreferences().getInt(key, INVALID_INT_VALUE);
    }

    /**
     * @param key   要保存的boolean类型数据的key
     * @param value boolean类型的value
     */
    public static void putBoolean(String key, boolean value) {
        key = encodString(key);
        getSharedPreferences().edit().putBoolean(key, value).commit();
    }

    /**
     * @param key 获取boolean类型数据的key
     * @return boolean类型的value
     */
    public static boolean getBoolean(String key) {
        key = encodString(key);
        return getSharedPreferences().getBoolean(key, INVALID_BOOLEAN_VALUE);
    }

    /**
     * @param key   要保存的float类型数据的key
     * @param value float类型的value
     */
    public static void putFloat(String key, float value) {
        key = encodString(key);
        getSharedPreferences().edit().putFloat(key, value).commit();
    }

    /**
     * @param key 获取float类型数据的key
     * @return float类型的value
     */
    public static float getFloat(String key) {
        key = encodString(key);
        return getSharedPreferences().getFloat(key, INVALID_FLOAT_VALUE);
    }

    /**
     * @param key   要保存的long类型数据的key
     * @param value long类型的value
     */
    public static void putLong(String key, long value) {
        key = encodString(key);
        getSharedPreferences().edit().putLong(key, value).commit();
    }

    /**
     * @param key 获取long类型数据的key
     * @return long类型的value
     */
    public static long getLong(String key) {
        key = encodString(key);
        return getSharedPreferences().getLong(key, INVALID_LONG_VALUE);
    }

    /**
     * @param key   要保存的Set集合的key
     * @param value Ste集合的value
     */
    public static void putSet(String key, Set<String> value) {
        key = encodString(key);
        getSharedPreferences().edit().putStringSet(key, value).commit();
    }

    /**
     * @param key 获取Set集合的key
     * @return Set集合的value
     */
    public static Set<String> getSet(String key) {
        key = encodString(key);
        return getSharedPreferences().getStringSet(key, null);
    }

    /**
     * @param key 获取任意类型数据的key
     * @return 任意类型的value
     */
    public static <T> T getObject(String key, Clreplaced<T> clreplacedOfT) {
        String str = getString(key);
        if (!TextUtils.isEmpty(str)) {
            return new Gson().fromJson(str, clreplacedOfT);
        } else {
            return null;
        }
    }

    /**
     * @param key    要保存的任意类型数据的key
     * @param object 任意类型的value
     */
    public static void putObject(String key, Object object) {
        if (object != null) {
            putString(key, new Gson().toJson(object));
        }
    }

    /**
     * @param key  要保存的List数据的key
     * @param list 需要保存的List数据
     * @param <T>
     */
    public static <T> void putList(String key, List<T> list) {
        if (list != null) {
            putString(key, new Gson().toJson(list));
        }
    }

    /**
     * @param key 获取list的key
     * @param <T>
     * @return t类型的list集合
     */
    public static <T> List<T> getList(String key, Clreplaced<T> clreplacedOfT) {
        String str = getString(key);
        if (!TextUtils.isEmpty(str)) {
            List<T> list = new ArrayList<>();
            Gson gson = new Gson();
            JsonArray arry = new JsonParser().parse(str).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                list.add(gson.fromJson(jsonElement, clreplacedOfT));
            }
            return list;
        } else {
            return null;
        }
    }

    /**
     * 删除指定key的数据
     *
     * @param key 要删除数据的key
     */
    public static void remove(String key) {
        if (contains(key)) {
            key = encodString(key);
            getSharedPreferences().edit().remove(key).commit();
        }
    }

    public static void removeList(String[] keys) {
        if (keys == null || keys.length == 0) {
            return;
        }
        for (int i = 0; i < keys.length; i++) {
            remove(keys[i]);
        }
    }

    public static void clear() {
        getSharedPreferences().edit().clear().commit();
    }

    /**
     * @param key 需要判断的key
     * @return 是否存在指定的key
     */
    public static boolean contains(String key) {
        key = encodString(key);
        return getSharedPreferences().contains(key);
    }

    /**
     * 将明文加密
     *
     * @param str 需要被加密的明文
     * @return 加密后的密文
     */
    private static String encodString(String str) {
        /*  try {
            byte[] bytes=str.getBytes("utf-8");
            return Base64.encodeToString(bytes,Base64.URL_SAFE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return str;//encrypt.encrypt(str);str;
        }*/
        return str;
    }

    /**
     * 将密文解析为明文
     *
     * @param str 需要解析的密文
     * @return 解密后的明文
     */
    private static String decodeString(String str) {
        /*try {
            byte[] bytes=str.getBytes("utf-8");
            return Conversion.bytesToHexString(Base64.decode(bytes,Base64.URL_SAFE));
        } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
            return str;
        }*/
        // encrypt.decrypt(str);
        return str;
    }
}

19 Source : SharedPreferencesUtil.java
with MIT License
from zhongjhATC

/**
 * 保存信息配置类
 * Created by zhongjh on 2018/8/7.
 */
clreplaced SharedPreferencesUtil {

    private SharedPreferences sharedPreferences;

    /*
     * 保存手机里面的名字
     */
    private SharedPreferences.Editor editor;

    @SuppressLint("CommitPrefEdits")
    SharedPreferencesUtil(Context context, String FILE_NAME) {
        sharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public void putString(String key, String object) {
        editor.putString(key, object);
        editor.commit();
    }

    public void putInt(String key, Integer object) {
        editor.putInt(key, object);
        editor.commit();
    }

    public void putBoolean(String key, Boolean object) {
        editor.putBoolean(key, object);
        editor.commit();
    }

    public void putFloat(String key, Float object) {
        editor.putFloat(key, object);
        editor.commit();
    }

    public void putLong(String key, Long object) {
        editor.putLong(key, object);
        editor.commit();
    }

    public String getString(String key, String defaultObject) {
        return sharedPreferences.getString(key, defaultObject);
    }

    public Integer getInt(String key, Integer defaultObject) {
        return sharedPreferences.getInt(key, defaultObject);
    }

    public Boolean getBoolean(String key, Boolean defaultObject) {
        return sharedPreferences.getBoolean(key, defaultObject);
    }

    public Float getFloat(String key, Float defaultObject) {
        return sharedPreferences.getFloat(key, defaultObject);
    }

    public Long getLong(String key, Long defaultObject) {
        return sharedPreferences.getLong(key, defaultObject);
    }

    /**
     * 移除某个key值已经对应的值
     */
    public void remove(String key) {
        editor.remove(key);
        editor.commit();
    }

    /**
     * 清除所有数据
     */
    public void clear() {
        editor.clear();
        editor.commit();
    }

    /**
     * 查询某个key是否存在
     */
    public Boolean contain(String key) {
        return sharedPreferences.contains(key);
    }

    /**
     * 返回所有的键值对
     */
    public Map<String, ?> getAll() {
        return sharedPreferences.getAll();
    }
}

19 Source : SpUtil.java
with Apache License 2.0
from zhkrb

/**
 * Created by cxf on 2018/9/17.
 * SharedPreferences 封装
 */
public clreplaced SpUtil {

    public static final String SECURITY_ENABLE = "security_enable";

    public static final String SAFEMODE = "safemode";

    public static final String LANGUAGE = "language";

    public static final String INDEX_VIDEO_LIST_MODE = "indexvideolistmode";

    public static final String VIEW_VIDEO_LIST_MODE = "indexvideolistmode";

    public static final String LIKE_VIDEO_LIST_MODE = "indexvideolistmode";

    public static final String GALLERY_MODE = "gallery_mode";

    public static final String SHOW_LIKE_BG = "show_like_bg";

    public static final String VERSION_CODE = "version_code";

    public static final String IGNORE_VERSION = "ignore_version";

    private static SpUtil sInstance;

    private SharedPreferences mSharedPreferences;

    private SpUtil() {
        mSharedPreferences = AppContext.sInstance.getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
    }

    public static SpUtil getInstance() {
        if (sInstance == null) {
            synchronized (SpUtil.clreplaced) {
                if (sInstance == null) {
                    sInstance = new SpUtil();
                }
            }
        }
        return sInstance;
    }

    /**
     * 保存一个字符串
     */
    public void setStringValue(String key, String value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * 获取一个字符串
     */
    public String getStringValue(String key) {
        return mSharedPreferences.getString(key, "");
    }

    /**
     * 保存一个数字
     */
    public void setIntValue(String key, int value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    /**
     * 获取数字
     */
    public int getIntValue(String key, int defValue) {
        return mSharedPreferences.getInt(key, defValue);
    }

    /**
     * 保存多个字符串
     */
    public void setMultiStringValue(Map<String, String> pairs) {
        if (pairs == null || pairs.size() == 0) {
            return;
        }
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        for (Map.Entry<String, String> entry : pairs.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                editor.putString(key, value);
            }
        }
        editor.apply();
    }

    /**
     * 获取多个字符串
     */
    public String[] getMultiStringValue(String... keys) {
        if (keys == null || keys.length == 0) {
            return null;
        }
        int length = keys.length;
        String[] result = new String[length];
        for (int i = 0; i < length; i++) {
            String temp = "";
            if (!TextUtils.isEmpty(keys[i])) {
                temp = mSharedPreferences.getString(keys[i], "");
            }
            result[i] = temp;
        }
        return result;
    }

    /**
     * 保存一个布尔值
     */
    public void setBooleanValue(String key, boolean value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    /**
     * 获取一个布尔值
     */
    public boolean getBooleanValue(String key) {
        return mSharedPreferences.getBoolean(key, false);
    }

    /**
     * 保存多个布尔值
     */
    public void setMultiBooleanValue(Map<String, Boolean> pairs) {
        if (pairs == null || pairs.size() == 0) {
            return;
        }
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        for (Map.Entry<String, Boolean> entry : pairs.entrySet()) {
            String key = entry.getKey();
            Boolean value = entry.getValue();
            if (!TextUtils.isEmpty(key)) {
                editor.putBoolean(key, value);
            }
        }
        editor.apply();
    }

    /**
     * 获取多个布尔值
     */
    public boolean[] getMultiBooleanValue(String[] keys) {
        if (keys == null || keys.length == 0) {
            return null;
        }
        int length = keys.length;
        boolean[] result = new boolean[length];
        for (int i = 0; i < length; i++) {
            boolean temp = false;
            if (!TextUtils.isEmpty(keys[i])) {
                temp = mSharedPreferences.getBoolean(keys[i], false);
            }
            result[i] = temp;
        }
        return result;
    }

    public void clear() {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.clear().apply();
    }

    public void removeValue(String... keys) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        for (String key : keys) {
            editor.remove(key);
        }
        editor.apply();
    }

    public void setLongValue(String key, long value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putLong(key, value);
        editor.apply();
    }

    public long getLongValue(String key, long defValue) {
        return mSharedPreferences.getLong(key, defValue);
    }
}

19 Source : SpUtil.java
with MIT License
from zhkrb

/**
 * @author zhkrb
 * @description:sharedPreferences工具类
 * @DATE: 2020/7/14 14:27
 */
public clreplaced SpUtil {

    private volatile static SpUtil sInstance;

    private SharedPreferences mSharedPreferences;

    private static final String INPUT_HISTORY = "input_history";

    private SpUtil(Context context) {
        mSharedPreferences = context.getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
    }

    public static SpUtil getInstance(Context context) {
        if (sInstance == null) {
            synchronized (SpUtil.clreplaced) {
                if (sInstance == null) {
                    sInstance = new SpUtil(context);
                }
            }
        }
        return sInstance;
    }

    /**
     * 保存一个字符串
     */
    public void setStringValue(String key, String value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * 获取一个字符串
     */
    public String getStringValue(String key) {
        return mSharedPreferences.getString(key, "");
    }

    public String getStringValue(String key, String defaultValue) {
        return mSharedPreferences.getString(key, defaultValue);
    }

    /**
     * 保存一个数字
     */
    public void setIntValue(String key, int value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    /**
     * 获取数字
     */
    public int getIntValue(String key, int defValue) {
        return mSharedPreferences.getInt(key, defValue);
    }

    /**
     * 保存多个字符串
     */
    public void setMultiStringValue(Map<String, String> pairs) {
        if (pairs == null || pairs.size() == 0) {
            return;
        }
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        for (Map.Entry<String, String> entry : pairs.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                editor.putString(key, value);
            }
        }
        editor.apply();
    }

    /**
     * 获取多个字符串
     */
    public String[] getMultiStringValue(String... keys) {
        if (keys == null || keys.length == 0) {
            return null;
        }
        int length = keys.length;
        String[] result = new String[length];
        for (int i = 0; i < length; i++) {
            String temp = "";
            if (!TextUtils.isEmpty(keys[i])) {
                temp = mSharedPreferences.getString(keys[i], "");
            }
            result[i] = temp;
        }
        return result;
    }

    /**
     * 保存一个布尔值
     */
    public void setBooleanValue(String key, boolean value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    /**
     * 获取一个布尔值
     */
    public boolean getBooleanValue(String key) {
        return mSharedPreferences.getBoolean(key, false);
    }

    public boolean getBooleanValue(String key, boolean defaultValue) {
        return mSharedPreferences.getBoolean(key, defaultValue);
    }

    /**
     * 保存多个布尔值
     */
    public void setMultiBooleanValue(Map<String, Boolean> pairs) {
        if (pairs == null || pairs.size() == 0) {
            return;
        }
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        for (Map.Entry<String, Boolean> entry : pairs.entrySet()) {
            String key = entry.getKey();
            Boolean value = entry.getValue();
            if (!TextUtils.isEmpty(key)) {
                editor.putBoolean(key, value);
            }
        }
        editor.apply();
    }

    /**
     * 获取多个布尔值
     */
    public boolean[] getMultiBooleanValue(String[] keys) {
        if (keys == null || keys.length == 0) {
            return null;
        }
        int length = keys.length;
        boolean[] result = new boolean[length];
        for (int i = 0; i < length; i++) {
            boolean temp = false;
            if (!TextUtils.isEmpty(keys[i])) {
                temp = mSharedPreferences.getBoolean(keys[i], false);
            }
            result[i] = temp;
        }
        return result;
    }

    public void clear() {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.clear().apply();
    }

    public void removeValue(String... keys) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        for (String key : keys) {
            editor.remove(key);
        }
        editor.apply();
    }

    public void setLongValue(String key, long value) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putLong(key, value);
        editor.apply();
    }

    public long getLongValue(String key, long defValue) {
        return mSharedPreferences.getLong(key, defValue);
    }

    public String getInputHistory() {
        return getStringValue(INPUT_HISTORY);
    }

    public void setInputHistory(String str) {
        setStringValue(INPUT_HISTORY, str);
    }
}

19 Source : PreferenceManager.java
with MIT License
from zhaobao

/**
 * Preference Manger
 * Created by zb on 18/12/2017.
 */
public clreplaced PreferenceManager {

    public static final String PREF_SETTINGS_HIDE_SYSTEM_APPS = "hide_system_apps";

    public static final String PREF_SETTINGS_HIDE_UNINSTALL_APPS = "hide_uninstall_apps";

    public static final String PREF_LIST_SORT = "sort_list";

    public static final String FCM_ID = "fcm_id";

    private static final String PREF_NAME = "preference_application";

    private static PreferenceManager mManager;

    private static SharedPreferences mShare;

    private PreferenceManager() {
    }

    public static void init(Context context) {
        mManager = new PreferenceManager();
        mShare = context.getApplicationContext().getSharedPreferences(PREF_NAME, 0);
    }

    public static PreferenceManager getInstance() {
        return mManager;
    }

    public void putBoolean(String key, boolean value) {
        mShare.edit().putBoolean(key, value).apply();
    }

    public void putInt(String key, int value) {
        mShare.edit().putInt(key, value).apply();
    }

    public boolean getBoolean(String key) {
        return mShare.getBoolean(key, false);
    }

    public int getInt(String key) {
        return mShare.getInt(key, 0);
    }

    public boolean getUninstallSettings(String key) {
        return mShare.getBoolean(key, true);
    }

    public boolean getSystemSettings(String key) {
        return mShare.getBoolean(key, true);
    }

    public void putString(String key, String value) {
        mShare.edit().putString(key, value).apply();
    }

    public String getString(String key) {
        return mShare.getString(key, "");
    }
}

19 Source : PluginInternalPreferencesStorage.java
with MIT License
from zhangyd-c

/**
 * Created by Nikolay Demyankov on 28.07.15.
 * <p/>
 * Utility clreplaced to store plugin internal preferences in shared preferences
 *
 * @see PluginInternalPreferences
 * @see IObjectPreferenceStorage
 * @see SharedPreferences
 */
public clreplaced PluginInternalPreferencesStorage implements IObjectPreferenceStorage<PluginInternalPreferences> {

    private static final String PREF_FILE_NAME = "chcp_plugin_config_pref";

    private static final String PREF_KEY = "config_json";

    private SharedPreferences preferences;

    /**
     * Clreplaced constructor
     *
     * @param context application context
     */
    public PluginInternalPreferencesStorage(Context context) {
        preferences = context.getSharedPreferences(PREF_FILE_NAME, 0);
    }

    @Override
    public boolean storeInPreference(PluginInternalPreferences config) {
        if (config == null) {
            return false;
        }
        preferences.edit().putString(PREF_KEY, config.toString()).apply();
        return true;
    }

    @Override
    public PluginInternalPreferences loadFromPreference() {
        final String configJson = preferences.getString(PREF_KEY, null);
        if (configJson == null) {
            return null;
        }
        return PluginInternalPreferences.fromJson(configJson);
    }
}

19 Source : PreferencesUtil.java
with Apache License 2.0
from zhangliangming

/**
 * 配置文件处理类
 * Created by zhangliangming on 2017/8/6.
 */
public clreplaced PreferencesUtil {

    private static final String PREFERENCE_NAME = "com.zlm.hp.sp";

    private static SharedPreferences preferences;

    /**
     * 保存数据到SharedPreferences配置文件
     *
     * @param context
     * @param key     关键字
     * @param data    要保存的数据
     */
    public static void saveValue(Context context, String key, Object data) {
        if (preferences == null) {
            preferences = context.getSharedPreferences(PREFERENCE_NAME, 0);
        }
        SharedPreferences.Editor editor = preferences.edit();
        if (data instanceof Boolean) {
            editor.putBoolean(key, (Boolean) data);
        } else if (data instanceof Integer) {
            editor.putInt(key, (Integer) data);
        } else if (data instanceof String) {
            editor.putString(key, (String) data);
        } else if (data instanceof Float) {
            editor.putFloat(key, (Float) data);
        } else if (data instanceof Long) {
            editor.putFloat(key, (Long) data);
        }
        // 提交修改
        editor.commit();
    }

    /**
     * 从SharedPreferences配置文件中获取数据
     *
     * @param context
     * @param key     关键字
     * @param defData 默认获取的数据
     * @return
     */
    public static Object getValue(Context context, String key, Object defData) {
        if (preferences == null) {
            preferences = context.getSharedPreferences(PREFERENCE_NAME, 0);
        }
        if (defData instanceof Boolean) {
            return preferences.getBoolean(key, (Boolean) defData);
        } else if (defData instanceof Integer) {
            return preferences.getInt(key, (Integer) defData);
        } else if (defData instanceof String) {
            return preferences.getString(key, (String) defData);
        } else if (defData instanceof Float) {
            return preferences.getFloat(key, (Float) defData);
        } else if (defData instanceof Long) {
            return preferences.getLong(key, (Long) defData);
        }
        return null;
    }
}

19 Source : SP.java
with Apache License 2.0
from zhanghacker

/**
 * 基础参数的操作
 */
public clreplaced SP {

    // 基础参数放置的数据库名称
    private static final String DBName = "zhangxiaoxiao";

    private static SP instance = null;

    private SharedPreferences sp;

    public SP(Context context) {
        sp = context.getSharedPreferences(DBName, Context.MODE_PRIVATE);
        instance = this;
    }

    public static SP getInstance(Context context) {
        if (instance == null)
            return new SP(context);
        return instance;
    }

    /**
     * 获取SP的实例
     */
    public SharedPreferences getSP() {
        return sp;
    }

    /**
     * 获取字符串
     *
     * @param key key值,要求全局唯一
     * @return 返回 Key 对应的 value,默认为 null
     */
    public String getString(String key) {
        return sp.getString("String-" + key, null);
    }

    /**
     * 获取字符串
     *
     * @param key      key值,要求全局唯一
     * @param defValue 默认值
     * @return 返回 Key 对应的 value,默认为 null
     */
    public String getString(String key, String defValue) {
        return sp.getString("String-" + key, defValue);
    }

    public void putString(String key, String value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("String-" + key, value);
        editor.commit();
    }

    /**
     * @param key
     * @return
     */
    public Boolean getBoolean(String key) {
        return sp.getBoolean("Boolean-" + key, false);
    }

    public Boolean getBoolean(String key, boolean defValue) {
        return sp.getBoolean("Boolean-" + key, defValue);
    }

    public void putBoolean(String key, Boolean value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("Boolean-" + key, value);
        editor.commit();
    }

    public Float getFloat(String key) {
        return sp.getFloat("Float-" + key, 0f);
    }

    public void putFloat(String key, Float value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat("Float-" + key, value);
        editor.commit();
    }

    public Integer getInt(String key, int defaultValue) {
        return sp.getInt("Int-" + key, defaultValue);
    }

    public Integer getInt(String key) {
        return getInt(key, 0);
    }

    public void putInt(String key, Integer value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("Int-" + key, value);
        editor.commit();
    }

    public Long getLong(String key) {
        return sp.getLong("Long-" + key, 0);
    }

    public void putLong(String key, Long value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong("Long-" + key, value);
        editor.commit();
    }

    public Set<String> getStringSet(String key) {
        return sp.getStringSet("StringSet-" + key, new HashSet<String>());
    }

    public void putStringSet(String key, Set<String> value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putStringSet("StringSet-" + key, value);
        editor.commit();
    }

    /**
     * 使用 fastJson 转成 json 数据存储
     *
     * @param key
     * @param value
     */
    public void putObject(String key, Object value) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("Object-" + key, value == null ? null : JSON.toJSONString(value));
        editor.commit();
    }

    /**
     * 获取存储的对象, 获取不到则返回 null
     * @param key
     * @param <T>
     * @return
     */
    public <T> T getObject(String key, Clreplaced<T> clazz) {
        String value = sp.getString("Object-" + key, null);
        if (null == value) {
            return null;
        }
        return JSON.parseObject(value, clazz);
    }

    public void putList(String key, List list) {
        String value = (list == null || list.size() == 0) ? "" : JSON.toJSONString(list);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("List-" + key, value);
        editor.commit();
    }

    public <T> List<T> getList(String key, Clreplaced<T> clazz) {
        String value = sp.getString("List-" + key, "");
        if (TextUtils.isEmpty(value))
            return new ArrayList<T>();
        try {
            return JSON.parseArray(value, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<T>();
        }
    }
}

19 Source : StationSdk.java
with MIT License
from zfman

/**
 * Created by Liu ZhuangFei on 2019/2/6.
 */
public clreplaced StationSdk implements Serializable {

    private static final String TAG = "StationSdk";

    protected IStationView stationView;

    protected StationJsSupport jsSupport;

    public static int SDK_VERSION = 3;

    protected SharedPreferences preferences;

    protected SharedPreferences.Editor editor;

    public void init(IStationView stationView, String space) {
        this.stationView = stationView;
        jsSupport = new StationJsSupport(stationView.getWebView());
        preferences = stationView.getSharedPreferences(space);
        editor = preferences.edit();
    }

    public StationJsSupport getJsSupport() {
        return jsSupport;
    }

    @Deprecated
    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setMinSupport(int minSupport) {
        Log.d(TAG, "setMinSupport: " + SDK_VERSION + ":min:" + minSupport);
        if (SDK_VERSION < minSupport) {
            stationView.showMessage("版本太低,不支持本服务站,请升级新版本!");
            stationView.finish();
        }
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void saveSchedules(String name, String json) {
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void toast(String msg) {
        stationView.showMessage(msg);
    }

    @Deprecated
    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void messageDialog(final String tag, final String replacedle, final String content, final String confirmText) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                AlertDialog.Builder builder = new AlertDialog.Builder(stationView.getContext()).setreplacedle(replacedle).setMessage(content).setPositiveButton(confirmText, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (dialogInterface != null) {
                            dialogInterface.dismiss();
                        }
                        jsSupport.callJs("onMessageDialogCallback('$0')", new String[] { tag });
                    }
                });
                builder.create().show();
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void simpleDialog(final String replacedle, final String content, final String okBtn, final String cancelBtn, final String callback) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                AlertDialog.Builder builder = new AlertDialog.Builder(stationView.getContext()).setreplacedle(replacedle).setMessage(content);
                if (cancelBtn != null) {
                    builder.setNegativeButton(cancelBtn, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (dialogInterface != null) {
                                dialogInterface.dismiss();
                            }
                            if (callback != null) {
                                jsSupport.callJs(callback + "(false)");
                            }
                        }
                    });
                }
                if (okBtn != null) {
                    builder.setPositiveButton(okBtn, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (dialogInterface != null) {
                                dialogInterface.dismiss();
                            }
                            if (callback != null) {
                                jsSupport.callJs(callback + "(true)");
                            }
                        }
                    });
                }
                builder.create().show();
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setreplacedle(final String replacedle) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setreplacedle(replacedle);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void putInt(final String key, final int value) {
        editor.putInt(key, value);
        editor.commit();
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public int getInt(final String key, final int def) {
        return preferences.getInt(key, def);
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void putString(final String key, final String value) {
        editor.putString(key, value);
        editor.commit();
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public String getString(final String key, final String defVal) {
        return preferences.getString(key, defVal);
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void commit() {
        editor.commit();
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void clear() {
        editor.clear();
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void jumpPage(final String page) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.jumpPage(page);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void loadingFinish() {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.notifyLoadingFinish();
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void loadingStart() {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.notifyLoadingStart();
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void goback() {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.goback();
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setStatusBarColor(final String color) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setStatusBarColor(color);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setFloatActionBarVisiable(final boolean b) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setFloatActionBarVisiable(b);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setActionBarVisiable(final boolean b) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setActionBarVisiable(b);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setActionBarAlpha(final float alpha) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setActionBarAlpha(alpha);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public int dp2px(final int dp) {
        return stationView.dp2px(dp);
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setActionBarColor(final String color) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setActionBarColor(color);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void setActionTextColor(final String color) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.setActionTextColor(color);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void registerClipBoard(final String regex) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.registerClipBoard(regex);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void unregisterClipBoard() {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.unregisterClipBoard();
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public boolean isRegisterClipBoard() {
        return stationView.isRegisterClipBoard();
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public String getClipContent() {
        return stationView.getClipContent();
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void getFromServer(final String moduleName, final String tag) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.getFromServer(moduleName, tag);
            }
        });
    }

    @JavascriptInterface
    @SuppressLint("SetJavaScriptEnabled")
    public void putToServer(final String moduleName, final String value, final String tag) {
        stationView.postThread(new IStationView.IMainRunner() {

            @Override
            public void done() {
                stationView.putToServer(moduleName, value, tag);
            }
        });
    }
}

19 Source : OnceUserManager.java
with MIT License
from zfman

/**
 * Created by Liu ZhuangFei on 2019/4/30.
 */
public clreplaced OnceUserManager {

    SharedPreferences sharedPreferences;

    SharedPreferences.Editor editor;

    static final String SP_ONCE_SPACE = "share_once_space";

    static final String KEY_ONCE_USERS = "key_once_users";

    public OnceUserManager(Context context) {
        sharedPreferences = context.getSharedPreferences(SP_ONCE_SPACE, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public boolean saveUser(OnceUser user) {
        List<OnceUser> userList = listUsers();
        OnceUser findUser = findUser(userList, user.getNumber());
        if (findUser != null) {
            return false;
        }
        userList.add(user);
        updateUsers(userList);
        return true;
    }

    public void deleteUser(String number) {
        List<OnceUser> userList = listUsers();
        OnceUser findUser = findUser(userList, number);
        if (findUser != null) {
            userList.remove(findUser);
            updateUsers(userList);
        }
    }

    public void applyUser(String number) {
        List<OnceUser> userList = listUsers();
        OnceUser findUser = findUser(userList, number);
        if (findUser != null) {
            userList.remove(findUser);
            userList.add(0, findUser);
            updateUsers(userList);
        }
    }

    public OnceUser findUser(List<OnceUser> userList, String number) {
        for (OnceUser u : userList) {
            if (u != null && u.getNumber().equals(number)) {
                return u;
            }
        }
        return null;
    }

    public List<OnceUser> listUsers() {
        List<OnceUser> list = new ArrayList<>();
        String json = sharedPreferences.getString(KEY_ONCE_USERS, null);
        if (!TextUtils.isEmpty(json)) {
            TypeToken<List<OnceUser>> token = new TypeToken<List<OnceUser>>() {
            };
            list = new Gson().fromJson(json, token.getType());
            if (list == null) {
                list = new ArrayList<>();
            }
        }
        return list;
    }

    public OnceUser listFirstUser() {
        List<OnceUser> list = listUsers();
        if (list == null || list.size() < 1)
            return null;
        return list.get(0);
    }

    public void updateUsers(List<OnceUser> userList) {
        if (userList != null) {
            String json = new Gson().toJson(userList);
            editor.putString(KEY_ONCE_USERS, json);
            editor.commit();
        }
    }

    public boolean hasLocalUser() {
        List<OnceUser> list = listUsers();
        if (list == null || list.size() == 0) {
            return false;
        }
        return true;
    }
}

19 Source : Settings.java
with MIT License
from zfdang

public clreplaced Settings {

    private final String TAG = "Settings";

    private final String Preference_Name = "TouchHelper_Config";

    private SharedPreferences mPreference;

    private SharedPreferences.Editor mEditor;

    private Gson mJson;

    // Singleton
    private static Settings ourInstance = new Settings();

    public static Settings getInstance() {
        return ourInstance;
    }

    private Settings() {
        initSettings();
    }

    private void initSettings() {
        mPreference = TouchHelperApp.getAppContext().getSharedPreferences(Preference_Name, Activity.MODE_PRIVATE);
        mEditor = mPreference.edit();
        mJson = new Gson();
        // init all settings from SharedPreferences
        bSkipAdNotification = mPreference.getBoolean(SKIP_AD_NOTIFICATION, true);
        // initial duration of skip ad process
        iSkipAdDuration = mPreference.getInt(SKIP_AD_DURATION, 4);
        // find all system packages, and set them as default value for whitelist
        PackageManager packageManager = TouchHelperApp.getAppContext().getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> ResolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        Set<String> pkgSystems = new HashSet<>();
        for (ResolveInfo e : ResolveInfoList) {
            if ((e.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
                pkgSystems.add(e.activityInfo.packageName);
            }
        }
        // init whitelist of packages
        // https://stackoverflow.com/questions/10720028/android-sharedpreferences-not-saving
        // Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
        setWhiteListPackages = new HashSet<String>(mPreference.getStringSet(WHITELIST_PACKAGE, pkgSystems));
        // init key words
        String json = mPreference.getString(KEY_WORDS_LIST, "[\"跳过\"]");
        if (json != null) {
            Type type = new TypeToken<ArrayList<String>>() {
            }.getType();
            listKeyWords = mJson.fromJson(json, type);
        } else {
            listKeyWords = new ArrayList<>();
        }
        // load activity widgets
        json = mPreference.getString(PACKAGE_WIDGETS, null);
        if (json != null) {
            Type type = new TypeToken<TreeMap<String, Set<PackageWidgetDescription>>>() {
            }.getType();
            mapPackageWidgets = mJson.fromJson(json, type);
        } else {
            mapPackageWidgets = new TreeMap<>();
        }
        // load activity positions
        json = mPreference.getString(PACKAGE_POSITIONS, null);
        if (json != null) {
            Type type = new TypeToken<TreeMap<String, PackagePositionDescription>>() {
            }.getType();
            mapPackagePositions = mJson.fromJson(json, type);
        } else {
            mapPackagePositions = new TreeMap<>();
        }
    }

    // notification on skip ads?
    private static final String SKIP_AD_NOTIFICATION = "SKIP_AD_NOTIFICATION";

    private boolean bSkipAdNotification;

    public boolean isSkipAdNotification() {
        return bSkipAdNotification;
    }

    public void setSkipAdNotification(boolean bSkipAdNotification) {
        if (this.bSkipAdNotification != bSkipAdNotification) {
            this.bSkipAdNotification = bSkipAdNotification;
            mEditor.putBoolean(SKIP_AD_NOTIFICATION, this.bSkipAdNotification);
            mEditor.apply();
        }
    }

    // duration of skip ad process
    private static final String SKIP_AD_DURATION = "SKIP_AD_DURATION";

    private int iSkipAdDuration;

    public int getSkipAdDuration() {
        return iSkipAdDuration;
    }

    public void setSkipAdDuration(int iSkipAdDuration) {
        if (this.iSkipAdDuration != iSkipAdDuration) {
            this.iSkipAdDuration = iSkipAdDuration;
            mEditor.putInt(SKIP_AD_DURATION, this.iSkipAdDuration);
            mEditor.apply();
        }
    }

    // whitelist of packages
    private static final String WHITELIST_PACKAGE = "WHITELIST_PACKAGE";

    private Set<String> setWhiteListPackages;

    public Set<String> getWhitelistPackages() {
        return setWhiteListPackages;
    }

    public void setWhitelistPackages(Set<String> pkgs) {
        setWhiteListPackages.clear();
        setWhiteListPackages.addAll(pkgs);
        // https://stackoverflow.com/questions/10720028/android-sharedpreferences-not-saving
        mEditor.putStringSet(WHITELIST_PACKAGE, new HashSet<String>(setWhiteListPackages));
        mEditor.apply();
    }

    // list of key words
    private static final String KEY_WORDS_LIST = "KEY_WORDS_LIST";

    private ArrayList<String> listKeyWords;

    public List<String> getKeyWordList() {
        return listKeyWords;
    }

    public String getKeyWordsreplacedtring() {
        return String.join(" ", listKeyWords);
    }

    public void setKeyWordList(String text) {
        String[] keys = text.split(" ");
        listKeyWords.clear();
        listKeyWords.addAll(Arrays.asList(keys));
        String json = mJson.toJson(listKeyWords);
        mEditor.putString(KEY_WORDS_LIST, json);
        mEditor.apply();
    }

    // map of key activity widgets
    private static final String PACKAGE_WIDGETS = "PACKAGE_WIDGETS";

    private Map<String, Set<PackageWidgetDescription>> mapPackageWidgets;

    public Map<String, Set<PackageWidgetDescription>> getPackageWidgets() {
        return mapPackageWidgets;
    }

    public void setPackageWidgets(Map<String, Set<PackageWidgetDescription>> map) {
        mapPackageWidgets = map;
        String json = mJson.toJson(mapPackageWidgets);
        // Log.d(TAG, json);
        mEditor.putString(PACKAGE_WIDGETS, json);
        mEditor.apply();
    }

    public String getPackageWidgetsInString() {
        String json = mJson.toJson(mapPackageWidgets);
        return json;
    }

    public boolean setPackageWidgetsInString(String value) {
        if (value != null) {
            try {
                Type type = new TypeToken<TreeMap<String, Set<PackageWidgetDescription>>>() {
                }.getType();
                mapPackageWidgets = mJson.fromJson(value, type);
                mEditor.putString(PACKAGE_WIDGETS, value);
                mEditor.apply();
            } catch (JsonSyntaxException e) {
                Log.d(TAG, Utilities.getTraceStackInString(e));
                return false;
            }
        }
        return false;
    }

    // map of key package positions
    private static final String PACKAGE_POSITIONS = "PACKAGE_POSITIONS";

    private Map<String, PackagePositionDescription> mapPackagePositions;

    public Map<String, PackagePositionDescription> getPackagePositions() {
        return mapPackagePositions;
    }

    public void setPackagePositions(Map<String, PackagePositionDescription> map) {
        mapPackagePositions = map;
        String json = mJson.toJson(mapPackagePositions);
        // Log.d(TAG, json);
        mEditor.putString(PACKAGE_POSITIONS, json);
        mEditor.apply();
    }
}

19 Source : EnhancedSharedPreferences.java
with GNU General Public License v3.0
from zeevy

public clreplaced EnhancedSharedPreferences implements SharedPreferences {

    private static EnhancedSharedPreferences enhancedSharedPreferences = null;

    private final SharedPreferences _sharedPreferences;

    private EnhancedSharedPreferences(SharedPreferences sharedPreferences) {
        _sharedPreferences = sharedPreferences;
    }

    public static EnhancedSharedPreferences getInstance(Context context, String prefsName) {
        if (enhancedSharedPreferences == null) {
            enhancedSharedPreferences = new EnhancedSharedPreferences(context.getSharedPreferences(prefsName, Context.MODE_PRIVATE));
        }
        return enhancedSharedPreferences;
    }

    @Override
    public Map<String, ?> getAll() {
        return _sharedPreferences.getAll();
    }

    @Override
    public String getString(String key, String defValue) {
        return _sharedPreferences.getString(key, defValue);
    }

    @Override
    public Set<String> getStringSet(String key, Set<String> defValues) {
        return _sharedPreferences.getStringSet(key, defValues);
    }

    @Override
    public int getInt(String key, int defValue) {
        return _sharedPreferences.getInt(key, defValue);
    }

    @Override
    public long getLong(String key, long defValue) {
        return _sharedPreferences.getLong(key, defValue);
    }

    @Override
    public float getFloat(String key, float defValue) {
        return _sharedPreferences.getFloat(key, defValue);
    }

    @Override
    public boolean getBoolean(String key, boolean defValue) {
        return _sharedPreferences.getBoolean(key, defValue);
    }

    @Override
    public boolean contains(String key) {
        return _sharedPreferences.contains(key);
    }

    @Override
    public Editor edit() {
        return new Editor(_sharedPreferences.edit());
    }

    @Override
    public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        _sharedPreferences.registerOnSharedPreferenceChangeListener(listener);
    }

    @Override
    public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        _sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener);
    }

    public Double getDouble(String key, Double defValue) {
        return Double.longBitsToDouble(_sharedPreferences.getLong(key, Double.doubleToRawLongBits(defValue)));
    }

    public static clreplaced Editor implements SharedPreferences.Editor {

        private final SharedPreferences.Editor _editor;

        public Editor(SharedPreferences.Editor editor) {
            _editor = editor;
        }

        private Editor ReturnEditor(SharedPreferences.Editor editor) {
            if (editor instanceof Editor)
                return (Editor) editor;
            return new Editor(editor);
        }

        @Override
        public Editor putString(String key, String value) {
            return ReturnEditor(_editor.putString(key, value));
        }

        @Override
        public Editor putStringSet(String key, Set<String> values) {
            return ReturnEditor(_editor.putStringSet(key, values));
        }

        @Override
        public Editor putInt(String key, int value) {
            return ReturnEditor(_editor.putInt(key, value));
        }

        @Override
        public Editor putLong(String key, long value) {
            return ReturnEditor(_editor.putLong(key, value));
        }

        @Override
        public Editor putFloat(String key, float value) {
            return ReturnEditor(_editor.putFloat(key, value));
        }

        @Override
        public Editor putBoolean(String key, boolean value) {
            return ReturnEditor(_editor.putBoolean(key, value));
        }

        @Override
        public Editor remove(String key) {
            return ReturnEditor(_editor.remove(key));
        }

        @Override
        public Editor clear() {
            return ReturnEditor(_editor.clear());
        }

        @Override
        public boolean commit() {
            return _editor.commit();
        }

        @Override
        public void apply() {
            _editor.apply();
        }

        public Editor putDouble(String key, double value) {
            return new Editor(_editor.putLong(key, Double.doubleToRawLongBits(value)));
        }
    }
}

19 Source : JavaScriptInterfaces.java
with GNU General Public License v3.0
from ZeeRooo

@SuppressWarnings("unused")
public clreplaced JavaScriptInterfaces {

    private final MainActivity mContext;

    private final SharedPreferences mPreferences;

    // Instantiate the interface and set the context
    public JavaScriptInterfaces(MainActivity c) {
        mContext = c;
        mPreferences = PreferenceManager.getDefaultSharedPreferences(c);
    }

    @JavascriptInterface
    public void getNums(final String notifications, final String messages, final String requests, final String feed) {
        final int notifications_int = Helpers.isInteger(notifications) ? Integer.parseInt(notifications) : 0;
        final int messages_int = Helpers.isInteger(messages) ? Integer.parseInt(messages) : 0;
        final int requests_int = Helpers.isInteger(requests) ? Integer.parseInt(requests) : 0;
        final int mr_int = Helpers.isInteger(feed) ? Integer.parseInt(feed) : 0;
        mContext.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                mContext.setNotificationNum(notifications_int);
                mContext.setMessagesNum(messages_int);
                mContext.setRequestsNum(requests_int);
                mContext.setMrNum(mr_int);
            }
        });
    }
}

19 Source : MFBResources.java
with GNU General Public License v3.0
from ZeeRooo

public void setColors(SharedPreferences sharedPreferences) {
    MFB.colorPrimary = sharedPreferences.getInt("colorPrimary", R.color.colorPrimary);
    MFB.colorPrimaryDark = sharedPreferences.getInt("colorPrimaryDark", R.color.colorPrimaryDark);
    MFB.colorAccent = sharedPreferences.getInt("colorAccent", R.color.colorAccent);
}

19 Source : SettingsFragment.java
with GNU General Public License v3.0
from ZeeRooo

public clreplaced SettingsFragment extends MFBPreferenceFragment implements Preference.OnPreferenceClickListener {

    private SharedPreferences mPreferences;

    private WorkManager workManager;

    private int red = 1, green = 1, blue = 1, colorPrimary;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.settings);
        mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        workManager = WorkManager.getInstance();
        // set onPreferenceClickListener for a few preferences
        findPreference("notifications_settings").setOnPreferenceClickListener(this);
        findPreference("navigation_menu_settings").setOnPreferenceClickListener(this);
        findPreference("more_and_credits").setOnPreferenceClickListener(this);
        findPreference("location_enabled").setOnPreferenceClickListener(this);
        findPreference("save_data").setOnPreferenceClickListener(this);
        findPreference("notif").setOnPreferenceClickListener(this);
        findPreference("color_picker").setOnPreferenceClickListener(this);
        findPreference("localeSwitcher").setOnPreferenceChangeListener((preference, o) -> {
            mPreferences.edit().putString("defaultLocale", o.toString()).apply();
            getActivity().recreate();
            return true;
        });
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        switch(preference.getKey()) {
            case "notifications_settings":
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.content_frame, new NotificationsSettingsFragment()).commit();
                return true;
            case "navigation_menu_settings":
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.content_frame, new NavigationMenuFragment()).commit();
                return true;
            case "more_and_credits":
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.content_frame, new MoreAndCreditsFragment()).commit();
                return true;
            case "location_enabled":
                ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 1);
                return true;
            case "save_data":
            case "notif":
                setScheduler();
                return true;
            case "color_picker":
                final AlertDialog mfbColorPickerDialog = new MFBDialog(getActivity()).create();
                final TextView previewTextView = new TextView(getActivity());
                previewTextView.setTextAppearance(getActivity(), R.style.MaterialAlertDialog_MaterialComponents_replacedle_Text);
                previewTextView.setTextSize(22.0f);
                previewTextView.setText(R.string.color_picker_replacedle);
                previewTextView.setPadding(24, 21, 24, 21);
                previewTextView.setBackgroundColor(Color.BLACK);
                mfbColorPickerDialog.setCustomreplacedle(previewTextView);
                final View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_color_picker, null);
                final EditText hexColorInput = rootView.findViewById(R.id.color_picker_hex);
                final Slider sliderRed = rootView.findViewById(R.id.color_picker_red_slider), sliderGreen = rootView.findViewById(R.id.color_picker_green_slider), sliderBlue = rootView.findViewById(R.id.color_picker_blue_slider);
                sliderRed.addOnChangeListener((slider, value, fromUser) -> {
                    red = (int) value;
                    setColor(previewTextView, hexColorInput);
                });
                sliderGreen.addOnChangeListener((slider, value, fromUser) -> {
                    green = (int) value;
                    setColor(previewTextView, hexColorInput);
                });
                sliderBlue.addOnChangeListener((slider, value, fromUser) -> {
                    blue = (int) value;
                    setColor(previewTextView, hexColorInput);
                });
                hexColorInput.setFilters(new InputFilter[] { new InputFilter.LengthFilter(6) });
                hexColorInput.setOnEditorActionListener((textView, i, keyEvent) -> {
                    colorPrimary = Color.parseColor("#" + textView.getText().toString().replace("#", ""));
                    previewTextView.setBackgroundColor(colorPrimary);
                    red = Color.red(colorPrimary);
                    green = Color.green(colorPrimary);
                    blue = Color.blue(colorPrimary);
                    sliderRed.setValue(red);
                    sliderGreen.setValue(green);
                    sliderBlue.setValue(blue);
                    return true;
                });
                final SwitchMaterial switchMaterial = rootView.findViewById(R.id.color_picker_dark_mode);
                switchMaterial.setOnCheckedChangeListener((compoundButton, b) -> {
                    switchMaterial.getThumbDrawable().setColorFilter(b ? MFB.colorAccent : Color.parseColor("#ECECEC"), PorterDuff.Mode.SRC_ATOP);
                    switchMaterial.getTrackDrawable().setColorFilter(b ? MFB.colorPrimaryDark : Color.parseColor("#B9B9B9"), PorterDuff.Mode.SRC_ATOP);
                });
                mfbColorPickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), (dialogInterface, i) -> mfbColorPickerDialog.dismiss());
                mfbColorPickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(android.R.string.ok), (dialogInterface, i) -> {
                    mfbColorPickerDialog.dismiss();
                    colorPrimary = Color.rgb(red, green, blue);
                    int colorAccent;
                    if (// it's too bright
                    ColorUtils.calculateLuminance(colorPrimary) > 0.8 || (ColorUtils.calculateLuminance(MFB.colorPrimary) < 0.5 && switchMaterial.isChecked()))
                        colorAccent = Color.BLACK;
                    else if (// it's too dark
                    ColorUtils.calculateLuminance(colorPrimary) < 0.01 && switchMaterial.isChecked())
                        colorAccent = Color.WHITE;
                    else
                        colorAccent = colorLighter(colorPrimary);
                    mPreferences.edit().putInt("colorPrimary", colorPrimary).apply();
                    mPreferences.edit().putInt("colorPrimaryDark", colorDarker(colorPrimary)).apply();
                    mPreferences.edit().putInt("colorAccent", colorAccent).apply();
                    mPreferences.edit().putBoolean("darkMode", switchMaterial.isChecked()).apply();
                    getActivity().recreate();
                // CookingAToast.cooking(getActivity(), getString(R.string.required_restart), Color.WHITE, colorPrimary, R.drawable.ic_error, true).show();
                });
                mfbColorPickerDialog.setView(rootView);
                mfbColorPickerDialog.show();
                return true;
            default:
                return false;
        }
    }

    private void setColor(TextView textView, EditText hexColorInput) {
        colorPrimary = Color.rgb(red, green, blue);
        textView.setBackgroundColor(colorPrimary);
        hexColorInput.setText(Integer.toHexString(colorPrimary).substring(2));
    }

    private float[] hsv = new float[3];

    private int colorDarker(int color) {
        Color.colorToHSV(color, hsv);
        // smaller = darker
        hsv[2] *= 0.8f;
        return Color.HSVToColor(hsv);
    }

    private int colorLighter(int color) {
        Color.colorToHSV(color, hsv);
        hsv[2] /= 0.8f;
        return Color.HSVToColor(hsv);
    }

    private void setScheduler() {
        if (mPreferences.getBoolean("notif", false) && !mPreferences.getBoolean("save_data", false))
            workManager.enqueue(new PeriodicWorkRequest.Builder(NotificationsService.clreplaced, Integer.valueOf(mPreferences.getString("notif_interval", "60000")), TimeUnit.MILLISECONDS).setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()).build());
        else
            workManager.cancelAllWork();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
            CookingAToast.cooking(getActivity(), getString(R.string.permission_denied), Color.WHITE, Color.parseColor("#ff4444"), R.drawable.ic_error, true).show();
    }
}

19 Source : NotificationsSettingsFragment.java
with GNU General Public License v3.0
from ZeeRooo

public clreplaced NotificationsSettingsFragment extends MFBPreferenceFragment implements Preference.OnPreferenceClickListener {

    private SharedPreferences sharedPreferences;

    private DatabaseHelper DBHelper;

    private ArrayList<String> blacklist = new ArrayList<>();

    private WorkManager workManager;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.notifications_settings);
        workManager = WorkManager.getInstance();
        if (getActivity() != null) {
            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            DBHelper = new DatabaseHelper(getActivity());
            findPreference("BlackList").setOnPreferenceClickListener(this);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                findPreference("ringtone").setOnPreferenceClickListener(this);
                findPreference("ringtone_msg").setOnPreferenceClickListener(this);
            } else
                findPreference("notification_channel_shortcut").setOnPreferenceClickListener(this);
            sharedPreferences.registerOnSharedPreferenceChangeListener((prefs, key) -> {
                switch(key) {
                    case "notif_interval":
                        workManager.cancelAllWork();
                        workManager.enqueue(new PeriodicWorkRequest.Builder(NotificationsService.clreplaced, Integer.valueOf(prefs.getString("notif_interval", "60000")), TimeUnit.MILLISECONDS).setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()).build());
                        break;
                    default:
                        break;
                }
            });
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        DBHelper.close();
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        switch(preference.getKey()) {
            case "notification_channel_shortcut":
                startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, getActivity().getPackageName()));
                break;
            case "ringtone":
            case "ringtone_msg":
                new MFBRingtoneDialog(getActivity(), sharedPreferences, preference.getKey()).show();
                break;
            case "BlackList":
                AlertDialog blacklistDialog = new MFBDialog(getActivity()).create();
                blacklistDialog.setreplacedle(R.string.blacklist_replacedle);
                final View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.chip_input, null);
                final Cursor cursor = DBHelper.getReadableDatabase().rawQuery("SELECT BL FROM mfb_table", null);
                while (cursor.moveToNext()) {
                    if (cursor.getString(0) != null)
                        addRemovableChip(cursor.getString(0), rootView);
                }
                final AutoCompleteTextView autoCompleteTextView = rootView.findViewById(R.id.preloadedTags);
                autoCompleteTextView.setAdapter(new ArrayAdapter<>(rootView.getContext(), android.R.layout.simple_dropdown_item_1line));
                autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
                    addRemovableChip((String) parent.gereplacedemAtPosition(position), rootView);
                    autoCompleteTextView.setText("");
                });
                autoCompleteTextView.setOnEditorActionListener((v, actionId, event) -> {
                    if ((actionId == EditorInfo.IME_ACTION_DONE)) {
                        addRemovableChip(v.getText().toString(), rootView);
                        autoCompleteTextView.setText("");
                        return true;
                    } else
                        return false;
                });
                blacklistDialog.setButton(DialogInterface.BUTTON_POSITIVE, getText(android.R.string.ok), (dialog, which) -> {
                    for (int position = 0; position < blacklist.size(); position++) {
                        DBHelper.addData(null, null, blacklist.get(position));
                    }
                    blacklist.clear();
                    if (!cursor.isClosed()) {
                        cursor.close();
                    }
                });
                blacklistDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getText(android.R.string.cancel), (dialog, which) -> {
                    blacklistDialog.dismiss();
                    blacklist.clear();
                    if (!cursor.isClosed()) {
                        cursor.close();
                    }
                });
                blacklistDialog.setView(rootView);
                blacklistDialog.show();
                return true;
        }
        return false;
    }

    private void addRemovableChip(String text, final View rootView) {
        blacklist.add(text);
        Chip chip = new Chip(rootView.getContext());
        chip.setChipBackgroundColor(ColorStateList.valueOf(MFB.colorAccent));
        // chip.setChipBackgroundColor(ColorStateList.valueOf(Theme.getColor(getActivity())));
        chip.setTextColor(MFB.textColor);
        chip.setText(text);
        chip.setTag(text);
        chip.setCloseIconVisible(true);
        ((ChipGroup) rootView.findViewById(R.id.tagsChipGroup)).addView(chip);
        chip.setOnCloseIconClickListener(v -> {
            ((ChipGroup) rootView.findViewById(R.id.tagsChipGroup)).removeView(v);
            blacklist.remove(v.getTag());
            DBHelper.remove(null, null, v.getTag().toString());
        });
    }
}

19 Source : MySharedPre.java
with Apache License 2.0
from Zane96

/**
 * Created by Zane on 2017/10/24.
 * Email: [email protected]
 */
public clreplaced MySharedPre {

    private SharedPreferences preferences;

    private SharedPreferences.Editor editor;

    private MySharedPre() {
        preferences = PreferenceManager.getDefaultSharedPreferences(App.getInstance());
        editor = preferences.edit();
    }

    private static final clreplaced SingletonHolder {

        private static final MySharedPre instance = new MySharedPre();
    }

    public static MySharedPre getInstance() {
        return SingletonHolder.instance;
    }

    public void putIpAddress(String ipAddress) {
        editor.putString("ipaddress", ipAddress);
        editor.commit();
    }

    public String getIpAddress(String defaultValue) {
        return preferences.getString("ipaddress", defaultValue);
    }

    public void putLastId(int id) {
        editor.putInt("lastid", id);
        editor.commit();
    }

    public int getLastId() {
        return preferences.getInt("lastid", 0);
    }
    // public void putOptions(int index, String options) {
    // editor.putString(String.format("%d_options", index), options);
    // editor.commit();
    // }
    // 
    // public String getOptions(int index, String defaultValue) {
    // return preferences.getString(String.format("%d_options", index), defaultValue);
    // }
    // 
    // public void putFilter(int index, String filter) {
    // editor.putString(String.format("%d_filter", index), filter);
    // editor.commit();
    // }
    // 
    // public String getFilter(int index, String defaultValue) {
    // return preferences.getString(String.format("%d_filter", index), defaultValue);
    // }
}

19 Source : AppConfig.java
with GNU General Public License v3.0
from z-chu

/**
 * 作者: 赵成柱 on 2016/7/13.
 * app设置管理类
 */
public clreplaced AppConfig {

    public final static String APP_CONFIG = "appConfig";

    // 默认存放图片的路径
    public static final String IMAGE_CACHE = AppContext.context().getCacheDir().getPath() + File.separator + "image-cache";

    // 默认存放数据缓存的路径
    public static final String DATA_CACHE = AppContext.context().getCacheDir().getPath() + File.separator + "data-cache";

    // 图片缓存的最大大小
    // public final static int IMAGE_CACHE_MAXSIZE = 20 * 1024 * 1024;
    // 默认存放WebView缓存的路径
    public final static String WEB_CACHE_PATH = AppContext.context().getCacheDir().getPath() + File.separator + "webCache";

    private final static String K_NIGHT_MODE = "night_mode";

    private static SharedPreferences sPref;

    /**
     * 清除WebView缓存
     */
    public static void clearWebViewCache() {
        FileUtil.deleteFile(WEB_CACHE_PATH);
    }

    private static SharedPreferences getPreferences() {
        if (sPref == null) {
            sPref = AppContext.context().getSharedPreferences(APP_CONFIG, Context.MODE_PRIVATE);
        }
        return sPref;
    }

    public static boolean isNightMode() {
        return getPreferences().getBoolean(K_NIGHT_MODE, false);
    }

    public static void setNightMode(boolean isNightMode) {
        getPreferences().edit().putBoolean(K_NIGHT_MODE, isNightMode).apply();
    }
}

19 Source : PreferencesHelper.java
with GNU General Public License v3.0
from z-chu

/**
 * Created by Chu on 2017/8/26.
 */
public clreplaced PreferencesHelper {

    private static final String K_SELECTED_ARTICLE_LABELS = "selected_book_labels";

    private static final String K_FIRST_START_APP = "first_start_app";

    private static final String K_BOOKCASE_SORT = "bookcase_sort";

    private static PreferencesHelper sPreferencesHelper;

    private SharedPreferences mPreferences;

    private Gson mGson;

    private PreferencesHelper(Context context) {
        mPreferences = context.getSharedPreferences("app-prefs", Context.MODE_PRIVATE);
        mGson = new Gson();
    }

    public static PreferencesHelper getInstance() {
        if (sPreferencesHelper == null) {
            sPreferencesHelper = new PreferencesHelper(AppContext.context());
        }
        return sPreferencesHelper;
    }

    public void setSelectedChannels(List<Channel> labels) {
        if (labels != null && labels.size() > 0) {
            for (int i = 0; i < labels.size(); i++) {
                if (labels.get(i) == null) {
                    labels.remove(i);
                }
            }
            if (labels.size() > 0) {
                mPreferences.edit().putString(K_SELECTED_ARTICLE_LABELS, mGson.toJson(labels)).apply();
                return;
            }
        }
        mPreferences.edit().remove(K_SELECTED_ARTICLE_LABELS).apply();
    }

    public List<Channel> getSelectedChannels() {
        String string = mPreferences.getString(K_SELECTED_ARTICLE_LABELS, null);
        if (string != null) {
            try {
                return mGson.fromJson(string, new TypeToken<List<Channel>>() {
                }.getType());
            } catch (Exception e) {
                Logger.e(e);
            }
        }
        return null;
    }

    public boolean isFirstStartApp() {
        return mPreferences.getBoolean(K_FIRST_START_APP, true);
    }

    public void setFirstStartApp(boolean b) {
        mPreferences.edit().putBoolean(K_FIRST_START_APP, b).apply();
    }

    public void setBookcaseSort(@BookcaseSort int bookcaseSort) {
        mPreferences.edit().putInt(K_BOOKCASE_SORT, bookcaseSort).apply();
    }

    @BookcaseSort
    public int getBookcaseSort() {
        @BookcaseSort
        int bookcaseSort = mPreferences.getInt(K_BOOKCASE_SORT, LATEST_READ_TIME);
        return bookcaseSort;
    }
}

19 Source : ConfigActivity.java
with Apache License 2.0
from Z-bm

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    isModified = true;
}

19 Source : ThingsCounts.java
with GNU General Public License v3.0
from ywwynm

/**
 * Created by ywwynm on 2015/7/11.
 * Model layer for database generated by table things_count
 */
@SuppressLint("CommitPrefEdits")
public clreplaced ThingsCounts {

    public static final String TAG = "ThingsCounts";

    public static final int ALL = Thing.DELETED + 1;

    private SharedPreferences mCounts;

    private static ThingsCounts sThingsCounts;

    private ThingsCounts(Context context) {
        mCounts = context.getSharedPreferences(Def.Meta.THINGS_COUNTS_NAME, Context.MODE_PRIVATE);
        if (mCounts.getInt("0_0", -1) == -1) {
            init();
        } else {
            checkSelf(context);
        }
    }

    public static ThingsCounts getInstance(Context context) {
        if (sThingsCounts == null) {
            synchronized (ThingsCounts.clreplaced) {
                if (sThingsCounts == null) {
                    sThingsCounts = new ThingsCounts(context.getApplicationContext());
                }
            }
        }
        return sThingsCounts;
    }

    private void checkSelf(Context context) {
        ThingDAO dao = ThingDAO.getInstance(context);
        for (int type = Thing.NOTE; type <= Thing.NOTIFY_EMPTY_DELETED; type++) {
            int totalCount = 0;
            for (int state = Thing.UNDERWAY; state <= Thing.DELETED; state++) {
                Cursor cursor = dao.getThingsCursor("type=" + type + " and state=" + state);
                int cursorCount = cursor.getCount();
                int prefCount = getCount(type, state);
                if (cursorCount != prefCount) {
                    setCounts(type, state, cursorCount);
                }
                totalCount += cursorCount;
                cursor.close();
            }
            if (getCount(type, ALL) < totalCount) {
                setCounts(type, ALL, totalCount);
            }
        }
    }

    public int getCount(int type, int state) {
        return mCounts.getInt(type + "_" + state, 0);
    }

    public int getThingsCountForActivityHeader(int limit) {
        int count = 0;
        switch(limit) {
            case Def.LimitForGettingThings.ALL_UNDERWAY:
                for (int i = NOTE; i <= WELCOME_UNDERWAY; i++) {
                    count += getCount(i, UNDERWAY);
                }
                count += getCount(NOTIFICATION_UNDERWAY, UNDERWAY);
                break;
            case Def.LimitForGettingThings.NOTE_UNDERWAY:
                count = getCount(NOTE, UNDERWAY) + getCount(WELCOME_NOTE, UNDERWAY) + getCount(NOTIFICATION_NOTE, UNDERWAY);
                break;
            case Def.LimitForGettingThings.REMINDER_UNDERWAY:
                count = getCount(REMINDER, UNDERWAY) + getCount(WELCOME_REMINDER, UNDERWAY) + getCount(NOTIFICATION_REMINDER, UNDERWAY);
                break;
            case Def.LimitForGettingThings.HABIT_UNDERWAY:
                count = getCount(HABIT, UNDERWAY) + getCount(WELCOME_HABIT, UNDERWAY) + getCount(NOTIFICATION_HABIT, UNDERWAY);
                break;
            case Def.LimitForGettingThings.GOAL_UNDERWAY:
                count = getCount(GOAL, UNDERWAY) + getCount(WELCOME_GOAL, UNDERWAY) + getCount(NOTIFICATION_GOAL, UNDERWAY);
                break;
            case Def.LimitForGettingThings.ALL_FINISHED:
                for (int i = Thing.NOTE; i <= Thing.NOTIFICATION_GOAL; i++) {
                    count += getCount(i, FINISHED);
                }
                break;
            case Def.LimitForGettingThings.ALL_DELETED:
                for (int i = Thing.NOTE; i <= Thing.NOTIFICATION_GOAL; i++) {
                    count += getCount(i, DELETED);
                }
                break;
        }
        return count;
    }

    public String getCompletionRate(int limit) {
        int[] counts = new int[2];
        switch(limit) {
            case Def.LimitForGettingThings.ALL_UNDERWAY:
            case Def.LimitForGettingThings.ALL_FINISHED:
            case Def.LimitForGettingThings.ALL_DELETED:
                for (int i = Thing.NOTE; i <= Thing.GOAL; i++) {
                    counts[0] += getCount(i, FINISHED);
                    counts[1] += getCount(i, ALL);
                }
                // counts[0] -= mCounts[Thing.HABIT][Thing.FINISHED];
                // counts[1] -= mCounts[Thing.HABIT][ALL];
                // counts[0] += mHabitFinished;
                // counts[1] += mHabitRecord;
                break;
            case Def.LimitForGettingThings.NOTE_UNDERWAY:
                counts[0] = getCount(NOTE, FINISHED);
                counts[1] = getCount(NOTE, ALL);
                break;
            case Def.LimitForGettingThings.REMINDER_UNDERWAY:
                counts[0] = getCount(REMINDER, FINISHED);
                counts[1] = getCount(REMINDER, ALL);
                break;
            case Def.LimitForGettingThings.HABIT_UNDERWAY:
                counts[0] = getCount(HABIT, FINISHED);
                counts[1] = getCount(HABIT, ALL);
                // counts[0] = mHabitFinished;
                // counts[1] = mHabitRecord;
                break;
            case Def.LimitForGettingThings.GOAL_UNDERWAY:
                counts[0] = getCount(GOAL, FINISHED);
                counts[1] = getCount(GOAL, ALL);
                break;
            default:
                break;
        }
        return LocaleUtil.getPercentStr(counts[0], counts[1]);
    }

    public void handleCreation(int type) {
        updateCounts(type, UNDERWAY, 1);
        updateCounts(type, ALL, 1);
    }

    public void handleUpdate(int typeBefore, int stateBefore, int typeAfter, int stateAfter, int count) {
        if (stateBefore != Thing.DELETED_FOREVER) {
            updateCounts(typeBefore, stateBefore, -count);
        }
        if (stateAfter != Thing.DELETED_FOREVER) {
            updateCounts(typeAfter, stateAfter, count);
            updateCounts(typeBefore, ALL, -count);
            updateCounts(typeAfter, ALL, count);
        }
    }

    // public boolean isNormal() {
    // for (int i = Thing.NOTE; i <= Thing.NOTIFY_EMPTY_DELETED; i++) {
    // for (int j = Thing.UNDERWAY; j <= Thing.DELETED_FOREVER; j++) {
    // if (mCounts[i][j] < 0 ||
    // mCounts[i][j] > mCounts[i][Thing.DELETED_FOREVER]) {
    // return false;
    // }
    // }
    // }
    // return true;
    // }
    private void updateCounts(int type, int state, int vary) {
        int count = getCount(type, state);
        count += vary;
        setCounts(type, state, count);
    }

    private void setCounts(int type, int state, int count) {
        mCounts.edit().putInt(type + "_" + state, count).commit();
    }

    private void init() {
        SharedPreferences.Editor editor = mCounts.edit();
        for (int i = NOTE; i <= NOTIFY_EMPTY_DELETED; i++) {
            for (int j = UNDERWAY; j <= ALL; j++) {
                editor.putInt(i + "_" + j, 0);
            }
        }
        for (int i = Thing.WELCOME_UNDERWAY; i <= Thing.WELCOME_GOAL; i++) {
            editor.putInt(i + "_" + UNDERWAY, 1);
            editor.putInt(i + "_" + ALL, 1);
        }
        editor.putInt(NOTIFY_EMPTY_FINISHED + "_" + UNDERWAY, 1);
        editor.putInt(NOTIFY_EMPTY_FINISHED + "_" + ALL, 1);
        editor.putInt(NOTIFY_EMPTY_DELETED + "_" + UNDERWAY, 1);
        editor.putInt(NOTIFY_EMPTY_DELETED + "_" + ALL, 1);
        editor.commit();
    }
}

19 Source : SettingsManager.java
with Apache License 2.0
from Yuloran

/**
 * Check that a setting has some value stored.
 */
public boolean isSet(String scope, String key) {
    synchronized (mLock) {
        SharedPreferences preferences = getPreferencesFromScope(scope);
        return preferences.contains(key);
    }
}

19 Source : Record.java
with Apache License 2.0
from YukiMatsumura

/**
 * Created by Yuki312 on 2017/07/01.
 */
@RestrictTo(LIBRARY)
public clreplaced Record {

    private static final int FREQ_DEFAULT = 0;

    private static final long RECENT_DEFAULT = 0L;

    private static final int COUNT_DEFAULT = 0;

    private final DenbunId id;

    private final SharedPreferences pref;

    public Record(@NonNull DenbunId id, @NonNull SharedPreferences pref) {
        this.id = nonNull(id);
        this.pref = nonNull(pref);
    }

    public State save(@NonNull State state) {
        pref.edit().putInt(Freq.of(id), state.frequency.value).apply();
        pref.edit().putLong(Recent.of(id), state.recent).apply();
        pref.edit().putInt(Count.of(id), state.count).apply();
        return load();
    }

    public State load() {
        return new State(id, Frequency.of(pref.getInt(Freq.of(id), FREQ_DEFAULT)), pref.getLong(Recent.of(id), RECENT_DEFAULT), pref.getInt(Count.of(id), COUNT_DEFAULT));
    }

    public boolean delete() {
        pref.edit().remove(Freq.of(id)).apply();
        pref.edit().remove(Recent.of(id)).apply();
        pref.edit().remove(Count.of(id)).apply();
        return true;
    }

    public boolean exist() {
        return pref.contains(Freq.of(id));
    }
}

19 Source : DaoImpl.java
with Apache License 2.0
from YukiMatsumura

/**
 * Created by Yuki312 on 2017/07/04.
 */
@RestrictTo(LIBRARY)
public clreplaced DaoImpl implements Dao {

    private SharedPreferences pref;

    public DaoImpl(@NonNull SharedPreferences preference) {
        pref = nonNull(preference);
    }

    @Override
    @NonNull
    public State find(@NonNull DenbunId id) {
        return new Record(id, pref).load();
    }

    @Override
    @NonNull
    public State update(@NonNull State state) {
        return new Record(state.id, pref).save(state);
    }

    @Override
    public boolean delete(@NonNull DenbunId id) {
        return new Record(id, pref).delete();
    }

    @Override
    public boolean exist(@NonNull DenbunId id) {
        return new Record(id, pref).exist();
    }
}

19 Source : DenbunConfig.java
with Apache License 2.0
from YukiMatsumura

/**
 * Denbun system-wide configuration.
 */
public final clreplaced DenbunConfig {

    public static final String PREF_NAME = "com.yuki312.denbun.xml";

    private SharedPreferences preference;

    private Dao.Provider daoProvider;

    public DenbunConfig(@NonNull Application app) {
        nonNull(app);
        // default config
        this.preference = app.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        this.daoProvider = new Dao.Provider() {

            @Override
            public Dao create(@NonNull SharedPreferences preference) {
                return new DaoImpl(nonNull(preference));
            }
        };
    }

    public DenbunConfig preference(@NonNull SharedPreferences preferences) {
        nonNull(preferences);
        this.preference = preferences;
        return this;
    }

    SharedPreferences preference() {
        return preference;
    }

    @VisibleForTesting(otherwise = PACKAGE_PRIVATE)
    public DenbunConfig daoProvider(@NonNull Dao.Provider provider) {
        nonNull(provider);
        this.daoProvider = provider;
        return this;
    }

    @VisibleForTesting(otherwise = PACKAGE_PRIVATE)
    public Dao.Provider daoProvider() {
        return daoProvider;
    }
}

19 Source : DenbunConfig.java
with Apache License 2.0
from YukiMatsumura

public DenbunConfig preference(@NonNull SharedPreferences preferences) {
    nonNull(preferences);
    this.preference = preferences;
    return this;
}

19 Source : EditSharedPreferences.java
with MIT License
from yuenov

public clreplaced EditSharedPreferences {

    // 设置信息
    public static final String STRING_REDSETTINGINFO = "STRING_REDSETTINGINFO";

    public static final String STRING_CATEGORYINFO = "STRING_CATEGORYINFO";

    public static final String STRING_SEARCHHISTORY = "searchHistory";

    // 阅读偏好
    public static final String STRING_READINGPREFERENCES = "ReadingPreferences";

    // 代理ip
    public static final String STRING_STRING_PROXYIP = "proxyIp";

    public static final String STRING_STRING_UUID = "uuid";

    public static final String STRING_STRING_UID = "uid";

    // 接口端口
    public static final String INT_INTERFACEPORT = "interFacePort";

    // 正在阅读的图书
    public static final String STRING_NOWREADBOOKID = "nowRead";

    private static SharedPreferences mySharedPreferences = null;

    public static SharedPreferences getSharedPreferencesInstance() {
        if (mySharedPreferences == null && null != MyApplication.getAppContext()) {
            mySharedPreferences = MyApplication.getAppContext().getSharedPreferences("app_info", Activity.MODE_PRIVATE);
        }
        return mySharedPreferences;
    }

    public static void writeBooleanToConfig(String key, boolean value) {
        getSharedPreferencesInstance().edit().putBoolean(key, value).apply();
    }

    public static boolean readBooleanFromConfig(String key, boolean defaultBoolean) {
        boolean defaultValue;
        try {
            defaultValue = getSharedPreferencesInstance().getBoolean(key, defaultBoolean);
        } catch (Exception e) {
            UtilityException.catchException(e);
            defaultValue = false;
        }
        return defaultValue;
    }

    public static void writeStringToConfig(String key, String value) {
        getSharedPreferencesInstance().edit().putString(key, value).apply();
    }

    public static String readStringFromConfig(String key) {
        String defaultValue;
        try {
            defaultValue = getSharedPreferencesInstance().getString(key, "");
        } catch (Exception e) {
            UtilityException.catchException(e);
            defaultValue = "";
        }
        return defaultValue;
    }

    public static void writeLongToConfig(String key, long value) {
        getSharedPreferencesInstance().edit().putLong(key, value).apply();
    }

    public static long readLongFromConfig(String key) {
        long defaultValue;
        try {
            defaultValue = getSharedPreferencesInstance().getLong(key, 0);
        } catch (Exception e) {
            UtilityException.catchException(e);
            defaultValue = 0;
        }
        return defaultValue;
    }

    public static void writeIntToConfig(String key, int value) {
        getSharedPreferencesInstance().edit().putInt(key, value).apply();
    }

    public static int readIntFromConfig(String key) {
        return readIntFromConfig(key, 0);
    }

    public static int readIntFromConfig(String key, int defaultInt) {
        int defaultValue;
        try {
            defaultValue = getSharedPreferencesInstance().getInt(key, defaultInt);
        } catch (Exception e) {
            UtilityException.catchException(e);
            defaultValue = 0;
        }
        return defaultValue;
    }

    /**
     * 设置:设置信息
     */
    public static void setReadSettingInfo(ReadSettingInfo readInfo) {
        try {
            SharedPreferences.Editor editor = getSharedPreferencesInstance().edit();
            editor.putString(STRING_REDSETTINGINFO, mHttpClient.GetGsonInstance().toJson(readInfo));
            editor.apply();
        } catch (Exception e) {
            UtilityException.catchException(e);
        }
    }

    /**
     * 获取:设置信息
     */
    public static ReadSettingInfo getReadSettingInfo() {
        ReadSettingInfo settingInfo = null;
        String strObj = getSharedPreferencesInstance().getString(STRING_REDSETTINGINFO, "");
        try {
            if (!TextUtils.isEmpty(strObj))
                settingInfo = (ReadSettingInfo) LibUtility.deSerializationToObject(strObj);
        } catch (Exception e) {
            UtilityException.catchException(e);
        }
        try {
            if (settingInfo == null)
                settingInfo = mHttpClient.GetGsonInstance().fromJson(strObj, ReadSettingInfo.clreplaced);
        } catch (Exception e) {
            UtilityException.catchException(e);
        }
        if (settingInfo == null) {
            settingInfo = new ReadSettingInfo();
        }
        return settingInfo;
    }

    public static void saveConfigInfo(Object obj) {
        try {
            SharedPreferences.Editor editor = getSharedPreferencesInstance().edit();
            editor.putString(STRING_CATEGORYINFO, mHttpClient.GetGsonInstance().toJson(obj));
            editor.apply();
        } catch (Exception e) {
            UtilityException.catchException(e);
        }
    }

    public static AppConfigInfo getConfigInfo() {
        AppConfigInfo settingInfo = null;
        String strObj = getSharedPreferencesInstance().getString(STRING_CATEGORYINFO, "");
        try {
            if (!TextUtils.isEmpty(strObj))
                settingInfo = (AppConfigInfo) LibUtility.deSerializationToObject(strObj);
        } catch (Exception e) {
            UtilityException.catchException(e);
        }
        try {
            if (settingInfo == null)
                settingInfo = mHttpClient.GetGsonInstance().fromJson(strObj, AppConfigInfo.clreplaced);
        } catch (Exception e) {
            UtilityException.catchException(e);
        }
        if (settingInfo == null) {
            settingInfo = new AppConfigInfo();
        }
        return settingInfo;
    }

    public static void addSearchHistory(String hotword) {
        try {
            List<String> lisHostory = getSearchHistory();
            if (lisHostory.size() > 10) {
                lisHostory.remove(lisHostory.size() - 1);
            }
            lisHostory.add(0, hotword);
            setSearchHistory(lisHostory);
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
    }

    public static List<String> getSearchHistory() {
        List<String> list = new ArrayList<>();
        try {
            String strObj = getSharedPreferencesInstance().getString(STRING_SEARCHHISTORY, "");
            if (!UtilitySecurity.isEmpty(strObj))
                list = mHttpClient.GetGsonInstance().fromJson(strObj, list.getClreplaced());
        } catch (Exception ex) {
            UtilityException.catchException(ex);
            list = new ArrayList<>();
        }
        return list;
    }

    public static void setSearchHistory(List<String> list) {
        try {
            SharedPreferences.Editor editor = getSharedPreferencesInstance().edit();
            editor.putString(STRING_SEARCHHISTORY, mHttpClient.GetGsonInstance().toJson(list));
            editor.apply();
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
    }

    public static ReadingPreferencesModel getReadingPreferences() {
        ReadingPreferencesModel model = null;
        try {
            model = mHttpClient.GetGsonInstance().fromJson(readStringFromConfig(STRING_READINGPREFERENCES), ReadingPreferencesModel.clreplaced);
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
        if (model == null)
            model = new ReadingPreferencesModel();
        return model;
    }

    public static void setReadingPreferences(ReadingPreferencesModel model) {
        try {
            if (model != null)
                writeStringToConfig(STRING_READINGPREFERENCES, mHttpClient.GetGsonInstance().toJson(model));
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
    }

    public static void setNowReadBook(BookBaseInfo bookBaseInfo) {
        try {
            EditSharedPreferences.writeStringToConfig(STRING_NOWREADBOOKID, mHttpClient.GetGsonInstance().toJson(bookBaseInfo));
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
    }

    public static void clearNowReadBook() {
        try {
            EditSharedPreferences.writeStringToConfig(STRING_NOWREADBOOKID, "");
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
    }

    public static BookBaseInfo getNowReadBook() {
        BookBaseInfo bookBaseInfo = null;
        try {
            String str = EditSharedPreferences.readStringFromConfig(STRING_NOWREADBOOKID);
            bookBaseInfo = mHttpClient.GetGsonInstance().fromJson(str, BookBaseInfo.clreplaced);
        } catch (Exception ex) {
            UtilityException.catchException(ex);
        }
        if (bookBaseInfo == null)
            bookBaseInfo = new BookBaseInfo();
        return bookBaseInfo;
    }
}

19 Source : XPreferencesUtils.java
with Apache License 2.0
from youth5201314

/**
 * 返回所有的键值对
 *
 * @return
 */
public static Map<String, ?> getAll() {
    SharedPreferences sp = XFrame.getContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.getAll();
}

19 Source : XPreferencesUtils.java
with Apache License 2.0
from youth5201314

/**
 * 查询某个key是否已经存在
 *
 * @param key
 * @return
 */
public static boolean contains(String key) {
    SharedPreferences sp = XFrame.getContext().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    return sp.contains(key);
}

19 Source : SharedPreferenceUtil.java
with Apache License 2.0
from YoungBill

public static long getKeyLong(String key, long defaultValue) {
    SharedPreferences longPreference = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    return longPreference.getLong(key, defaultValue);
}

19 Source : SharedPreferenceUtil.java
with Apache License 2.0
from YoungBill

public static boolean getKeyBoolean(String key, boolean defaultValue) {
    SharedPreferences booleanPreference = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    return booleanPreference.getBoolean(key, defaultValue);
}

19 Source : SharedPreferenceUtil.java
with Apache License 2.0
from YoungBill

public static int getKeyInt(String key, int defaultValue) {
    SharedPreferences intPreference = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    return intPreference.getInt(key, defaultValue);
}

19 Source : SPUtils.java
with Apache License 2.0
from youlookwhat

/**
 * 获取long的value
 */
public static long getLong(String key, long defValue) {
    SharedPreferences sharedPreference = getSharedPreference(CONFIG);
    return sharedPreference.getLong(key, defValue);
}

See More Examples