androidx.preference.PreferenceManager Java Examples

The following examples show how to use androidx.preference.PreferenceManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReceiverAutostart.java    From NetGuard with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
    Log.i(TAG, "Received " + intent);
    Util.logExtras(intent);

    String action = (intent == null ? null : intent.getAction());
    if (Intent.ACTION_BOOT_COMPLETED.equals(action) || Intent.ACTION_MY_PACKAGE_REPLACED.equals(action))
        try {
            // Upgrade settings
            upgrade(true, context);

            // Start service
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            if (prefs.getBoolean("enabled", false))
                ServiceSinkhole.start("receiver", context);
            else if (prefs.getBoolean("show_stats", false))
                ServiceSinkhole.run("receiver", context);

            if (Util.isInteractive(context))
                ServiceSinkhole.reloadStats("receiver", context);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
}
 
Example #2
Source File: ActivitySettings.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    checkPermissions(null);

    // Listen for preference changes
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for interactive state changes
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
}
 
Example #3
Source File: DatabaseHelper.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
private DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    prefs = PreferenceManager.getDefaultSharedPreferences(context);

    if (!once) {
        once = true;

        File dbfile = context.getDatabasePath(DB_NAME);
        if (dbfile.exists()) {
            Log.w(TAG, "Deleting " + dbfile);
            dbfile.delete();
        }

        File dbjournal = context.getDatabasePath(DB_NAME + "-journal");
        if (dbjournal.exists()) {
            Log.w(TAG, "Deleting " + dbjournal);
            dbjournal.delete();
        }
    }
}
 
Example #4
Source File: AdapterAccount.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
AdapterAccount(final Fragment parentFragment, boolean settings) {
    this.parentFragment = parentFragment;
    this.settings = settings;

    this.context = parentFragment.getContext();
    this.owner = parentFragment.getViewLifecycleOwner();
    this.inflater = LayoutInflater.from(context);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean highlight_unread = prefs.getBoolean("highlight_unread", true);
    this.colorUnread = Helper.resolveColor(context, highlight_unread ? R.attr.colorUnreadHighlight : android.R.attr.textColorPrimary);
    this.textColorSecondary = Helper.resolveColor(context, android.R.attr.textColorSecondary);

    this.DTF = Helper.getDateTimeInstance(context, DateFormat.SHORT, DateFormat.SHORT);

    setHasStableIds(true);

    owner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroyed() {
            Log.d(AdapterAccount.this + " parent destroyed");
            AdapterAccount.this.parentFragment = null;
        }
    });
}
 
Example #5
Source File: ActivitySettings.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    checkPermissions(null);

    // Listen for preference changes
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for interactive state changes
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
}
 
Example #6
Source File: ActivitySettings.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private boolean checkPermissions(String name) {
    PreferenceScreen screen = getPreferenceScreen();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Check if permission was revoked
    if ((name == null || "disable_on_call".equals(name)) && prefs.getBoolean("disable_on_call", false))
        if (!Util.hasPhoneStatePermission(this)) {
            prefs.edit().putBoolean("disable_on_call", false).apply();
            ((TwoStatePreference) screen.findPreference("disable_on_call")).setChecked(false);

            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_CALL);

            if (name != null)
                return false;
        }

    return true;
}
 
Example #7
Source File: FragmentOptions.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private void onExit() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    boolean setup_reminder = prefs.getBoolean("setup_reminder", true);

    boolean hasPermissions = hasPermission(Manifest.permission.READ_CONTACTS);
    Boolean isIgnoring = Helper.isIgnoringOptimizations(getContext());

    if (!setup_reminder ||
            (hasPermissions && (isIgnoring == null || isIgnoring)))
        super.finish();
    else {
        FragmentDialogStill fragment = new FragmentDialogStill();
        fragment.setTargetFragment(this, ActivitySetup.REQUEST_STILL);
        fragment.show(getParentFragmentManager(), "setup:still");
    }
}
 
Example #8
Source File: StartupActivity.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    fetchArchivesFromNetwork();

    final String startActivityPref = getString(R.string.start_activity_pref);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    final String act = prefs.getString(startActivityPref, getDefaultStartupActivity());
    final Class c = startupActivities.get(act) == null ? startupActivities.get(getDefaultStartupActivity()) : startupActivities.get(act);

    final Bundle args = getIntent().getExtras();
    final Intent i = new Intent(this, c);

    if (args != null) {
        i.putExtras(args);
    }
    startActivity(i);

    finish();
}
 
Example #9
Source File: ServiceSinkhole.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
private void startStats() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSinkhole.this);
    boolean enabled = (!stats && prefs.getBoolean("show_stats", false));
    Log.i(TAG, "Stats start enabled=" + enabled);
    if (enabled) {
        when = new Date().getTime();
        t = -1;
        tx = -1;
        rx = -1;
        gt.clear();
        gtx.clear();
        grx.clear();
        mapUidBytes.clear();
        stats = true;
        updateStats();
    }
}
 
Example #10
Source File: OdysseyMainActivity.java    From odyssey with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onStartSleepTimer(final long durationMS, final boolean stopAfterCurrent) {
    try {
        // save used duration to initialize the duration picker next time with this value
        SharedPreferences.Editor sharedPrefEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        sharedPrefEditor.putLong(getString(R.string.pref_last_used_sleep_timer_key), durationMS);
        sharedPrefEditor.putBoolean(getString(R.string.pref_last_used_sleep_timer_stop_after_current_key), stopAfterCurrent);
        sharedPrefEditor.apply();

        getPlaybackService().startSleepTimer(durationMS, stopAfterCurrent);

        // show a snackbar to inform the user that the sleep timer is now set
        View layout = findViewById(R.id.drawer_layout);
        if (layout != null) {
            Snackbar sb = Snackbar.make(layout, R.string.snackbar_sleep_timer_confirmation_message, Snackbar.LENGTH_SHORT);
            // style the snackbar text
            TextView sbText = sb.getView().findViewById(com.google.android.material.R.id.snackbar_text);
            sbText.setTextColor(ThemeUtils.getThemeColor(this, R.attr.odyssey_color_text_accent));
            sb.show();
        }
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example #11
Source File: WorkerFts.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
static void init(Context context, boolean immediately) {
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean fts = prefs.getBoolean("fts", true);
        boolean pro = ActivityBilling.isPro(context);
        if (fts && pro) {
            Log.i("Queuing " + getName());

            OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(WorkerFts.class);
            if (!immediately)
                builder.setInitialDelay(INDEX_DELAY, TimeUnit.SECONDS);
            OneTimeWorkRequest workRequest = builder.build();

            WorkManager.getInstance(context)
                    .enqueueUniqueWork(getName(), ExistingWorkPolicy.REPLACE, workRequest);

            Log.i("Queued " + getName());
        } else if (immediately)
            cancel(context);
    } catch (IllegalStateException ex) {
        // https://issuetracker.google.com/issues/138465476
        Log.w(ex);
    }
}
 
Example #12
Source File: MainActivity.java    From Android-Developer-Fundamentals-Version-2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, OrderActivity.class);
            intent.putExtra(EXTRA_MESSAGE, mOrderMessage);
            startActivity(intent);
        }
    });

    PreferenceManager.setDefaultValues(this, R.xml.sync_preferences, false);
    PreferenceManager.setDefaultValues(this, R.xml.general_preferences, false);
    PreferenceManager.setDefaultValues(this, R.xml.notification_preferences, false);
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String marketPref = sharedPreferences.getString("sync_frequency", "-1");
    displayToast(marketPref);
}
 
Example #13
Source File: ServiceUI.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private void onFlag(long id) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean threading = prefs.getBoolean("threading", true);

    DB db = DB.getInstance(this);
    try {
        db.beginTransaction();

        EntityMessage message = db.message().getMessage(id);
        if (message == null)
            return;

        List<EntityMessage> messages = db.message().getMessagesByThread(
                message.account, message.thread, threading ? null : id, message.folder);
        for (EntityMessage threaded : messages) {
            EntityOperation.queue(this, threaded, EntityOperation.FLAG, true);
            EntityOperation.queue(this, threaded, EntityOperation.SEEN, true);
        }

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example #14
Source File: ActivitySettings.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private boolean checkPermissions(String name) {
    PreferenceScreen screen = getPreferenceScreen();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Check if permission was revoked
    if ((name == null || "disable_on_call".equals(name)) && prefs.getBoolean("disable_on_call", false))
        if (!Util.hasPhoneStatePermission(this)) {
            prefs.edit().putBoolean("disable_on_call", false).apply();
            ((TwoStatePreference) screen.findPreference("disable_on_call")).setChecked(false);

            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_CALL);

            if (name != null)
                return false;
        }

    return true;
}
 
Example #15
Source File: WalletFragment.java    From lbry-android with MIT License 6 votes vote down vote up
public void generateNewAddress() {
    WalletAddressUnusedTask task = new WalletAddressUnusedTask(new WalletAddressUnusedTask.WalletAddressUnusedHandler() {
        @Override
        public void beforeStart() {
            Helper.setViewEnabled(buttonGetNewAddress, false);
        }
        @Override
        public void onSuccess(String newAddress) {
            Context context = getContext();
            if (context != null) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
                sp.edit().putString(MainActivity.PREFERENCE_KEY_INTERNAL_WALLET_RECEIVE_ADDRESS, newAddress).apply();
            }
            Helper.setViewText(textWalletReceiveAddress, newAddress);
            Helper.setViewEnabled(buttonGetNewAddress, true);
        }

        @Override
        public void onError(Exception error) {
            Helper.setViewEnabled(buttonGetNewAddress, true);
        }
    });
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #16
Source File: MeasurementPreferences.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.measurement_preferences, rootKey);

    setHasOptionsMenu(true);

    Preference deleteAll = findPreference(PREFERENCE_KEY_DELETE_ALL);
    deleteAll.setOnPreferenceClickListener(new onClickListenerDeleteAll());

    measurementCategory = (PreferenceCategory) findPreference(PREFERENCE_KEY_MEASUREMENTS);

    Preference resetOrder = findPreference(PREFERENCE_KEY_RESET_ORDER);
    resetOrder.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            PreferenceManager.getDefaultSharedPreferences(getActivity()).edit()
                    .remove(MeasurementView.PREF_MEASUREMENT_ORDER).apply();
            updateMeasurementPreferences();
            return true;
        }
    });

    updateMeasurementPreferences();
}
 
Example #17
Source File: ArtworkManager.java    From odyssey with GNU General Public License v3.0 6 votes vote down vote up
private ArtworkManager(Context context) {

        mDBManager = ArtworkDatabaseManager.getInstance(context);

        mArtistListeners = new ArrayList<>();
        mAlbumListeners = new ArrayList<>();

        ConnectionStateReceiver receiver = new ConnectionStateReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(receiver, filter);

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        mArtistProvider = sharedPref.getString(context.getString(R.string.pref_artist_provider_key), context.getString(R.string.pref_artwork_provider_artist_default));
        mAlbumProvider = sharedPref.getString(context.getString(R.string.pref_album_provider_key), context.getString(R.string.pref_artwork_provider_album_default));
        mWifiOnly = sharedPref.getBoolean(context.getString(R.string.pref_download_wifi_only_key), context.getResources().getBoolean(R.bool.pref_download_wifi_default));
        mUseLocalImages = sharedPref.getBoolean(context.getString(R.string.pref_artwork_use_local_images_key), context.getResources().getBoolean(R.bool.pref_artwork_use_local_images_default));
    }
 
Example #18
Source File: PreferencesFragment.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    //Inject current auto theme status since it isn't managed by PreferencesKeys.AUTO_THEME key
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(requireContext());
    prefs.edit().putBoolean(PreferencesKeys.AUTO_THEME, Theme.getInstance(requireContext()).getThemeMode() == Theme.Mode.AUTO_LIGHT_DARK).apply();
    super.onCreate(savedInstanceState);
}
 
Example #19
Source File: FragmentFolders.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private void onMenuShowFlagged() {
    show_flagged = !show_flagged;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    prefs.edit().putBoolean("flagged_folders", show_flagged).apply();

    getActivity().invalidateOptionsMenu();
    adapter.setShowFlagged(show_flagged);
}
 
Example #20
Source File: FirstRunActivity.java    From lbry-android with MIT License 5 votes vote down vote up
private void finishFirstRun() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    sp.edit().putBoolean(MainActivity.PREFERENCE_KEY_INTERNAL_FIRST_RUN_COMPLETED, true).apply();

    // first_run_completed event
    LbryAnalytics.logEvent(LbryAnalytics.EVENT_FIRST_RUN_COMPLETED);
    finish();
}
 
Example #21
Source File: App.java    From Ruisi with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    //初始化http
    HttpUtil.init(getApplicationContext());

    //清空消息数据库
    MyDB myDB = new MyDB(context);
    //最多缓存2000条历史纪录
    myDB.deleteOldHistory(2000);

    SharedPreferences shp = PreferenceManager.getDefaultSharedPreferences(context);
    // 自定义外网睿思服务器地址
    String customOutServerAddr = shp.getString("setting_rs_out_server_addr", App.BASE_URL_ME).trim();
    if (customOutServerAddr.length() > 0) {
        if (!customOutServerAddr.startsWith("http://")) {
            customOutServerAddr = "http://" + customOutServerAddr;
        }

        if (!customOutServerAddr.endsWith("/")) {
            customOutServerAddr += "/";
        }

        Log.i("APP", "设置外网服务器地址:" + customOutServerAddr);
        BASE_URL_ME = customOutServerAddr;
    }

    regReceiver();

    CrashReport.initCrashReport(getApplicationContext(), "04a96747f8", false);
}
 
Example #22
Source File: ServiceSinkhole.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
private void nativeExit(String reason) {
    Log.w(TAG, "Native exit reason=" + reason);
    if (reason != null) {
        showErrorNotification(reason);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putBoolean("enabled", false).apply();
        WidgetMain.updateWidgets(this);
    }
}
 
Example #23
Source File: DarkThemeApplication.java    From android-DarkTheme with Apache License 2.0 5 votes vote down vote up
public void onCreate() {
    super.onCreate();
    SharedPreferences sharedPreferences =
            PreferenceManager.getDefaultSharedPreferences(this);
    String themePref = sharedPreferences.getString("themePref", ThemeHelper.DEFAULT_MODE);
    ThemeHelper.applyTheme(themePref);
}
 
Example #24
Source File: NotesDatabase.java    From nextcloud-notes with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Modifies the sorting method for one category, the category can be normal category or
 * one of "All notes", "Favorite", and "Uncategorized".
 * If category is one of these three, sorting method will be modified in android.content.SharedPreference.
 * The user can determine use which sorting method to show the notes for a category.
 * When the user changes the sorting method, this method should be called.
 *
 * @param accountId     The user accountID
 * @param category      The category to be modified
 * @param sortingMethod The sorting method in {@link CategorySortingMethod} enum format
 */
public void modifyCategoryOrder(
        long accountId, Category category, CategorySortingMethod sortingMethod) {
    validateAccountId(accountId);

    final Context ctx = getContext().getApplicationContext();
    final SharedPreferences.Editor sp = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
    int orderIndex = sortingMethod.getCSMID();
    if (category.category == null) {
        if (category.favorite != null && category.favorite) {
            // Favorite
            sp.putInt(ctx.getString(R.string.action_sorting_method) +
                            ' ' + ctx.getString(R.string.label_favorites),
                    orderIndex);
        } else {
            // All notes
            sp.putInt(ctx.getString(R.string.action_sorting_method) +
                            ' ' + ctx.getString(R.string.label_all_notes),
                    orderIndex);
        }
    } else if (category.category.isEmpty()) {
        // Uncategorized
        sp.putInt(ctx.getString(R.string.action_sorting_method) +
                        ' ' + ctx.getString(R.string.action_uncategorized),
                orderIndex);
    } else {
        modifyCategoryOrderByTitle(accountId, category.category, sortingMethod);
        return;
    }
    sp.apply();
}
 
Example #25
Source File: MimiUtil.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public void init(final Context context) {

        if (ready) {
            return;
        }

        this.context = context;

        final SharedPreferences sh = PreferenceManager.getDefaultSharedPreferences(context);

        final String themeShadePrefString = context.getString(R.string.theme_pref);
        final String themeColorPrefString = context.getString(R.string.theme_color_pref);
        int themeId = Integer.valueOf(sh.getString(themeShadePrefString, "0"));
        int colorId = Integer.valueOf(sh.getString(themeColorPrefString, "0"));

        setCurrentTheme(themeId, colorId);
        Log.i(LOG_TAG, "Set theme: id=" + themeId + ", resource=" + getThemeResourceId());

//        if (boardOrderPrefString == null) {
//            boardOrderPrefString = context.getString(R.string.board_order_pref);
//        }

        cacheDir = context.getCacheDir();

        nextLoaderId = 0;
        loaderIdMap = new HashMap<>();

        executorPool = new ThreadPoolExecutor(THREAD_POOL_CORE_SIZE,
                THREAD_POOL_MAX_SIZE,
                THREAD_POOL_KEEP_ALIVE,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(THREAD_POOL_CORE_SIZE));

        quoteColor = sh.getInt(context.getString(R.string.quote_color_pref), context.getResources().getColor(R.color.quote));
        replyColor = sh.getInt(context.getString(R.string.reply_color_pref), context.getResources().getColor(R.color.reply));
        highlightColor = sh.getInt(context.getString(R.string.highlight_color_pref), context.getResources().getColor(R.color.reply_highlight));
        linkColor = sh.getInt(context.getString(R.string.link_color_pref), context.getResources().getColor(R.color.link));

        ready = true;
    }
 
Example #26
Source File: ThreeDSecureVerificationTest.java    From braintree_android with MIT License 5 votes vote down vote up
@Before
public void setup() {
    super.setup();
    onDevice(withText("Credit or Debit Cards")).waitForEnabled().perform(click());

    PreferenceManager.getDefaultSharedPreferences(getTargetContext())
            .edit()
            .putBoolean("enable_three_d_secure", true)
            .commit();
}
 
Example #27
Source File: ActivitySettings.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    PreferenceScreen screen = getPreferenceScreen();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    boolean granted = (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);

    if (requestCode == REQUEST_CALL) {
        prefs.edit().putBoolean("disable_on_call", granted).apply();
        ((TwoStatePreference) screen.findPreference("disable_on_call")).setChecked(granted);
    }

    if (granted)
        ServiceSinkhole.reload("permission granted", this, false);
}
 
Example #28
Source File: PreferencesFastFragment.java    From InviZible with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void changeTheme() {
    new Handler().post(() -> {

        if (getActivity() == null) {
            return;
        }

        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        try {
            String theme = defaultSharedPreferences.getString("pref_fast_theme", "4");

            switch (theme) {
                case "1":
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    break;
                case "2":
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    break;
                case "3":
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_TIME);
                    break;
                case "4":
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
                    break;
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "PreferencesFastFragment changeTheme exception " + e.getMessage() + " " + e.getCause());
        }

        activityCurrentRecreate();
    });

}
 
Example #29
Source File: AllContentFragment.java    From lbry-android with MIT License 5 votes vote down vote up
public void onPause() {
    Context context = getContext();
    if (context != null) {
        ((MainActivity) context).removeDownloadActionListener(this);
    }
    PreferenceManager.getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(this);
    super.onPause();
}
 
Example #30
Source File: FragmentOptionsSynchronize.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private void onMenuDefault() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    SharedPreferences.Editor editor = prefs.edit();
    for (String option : RESET_OPTIONS)
        editor.remove(option);
    editor.apply();
    ToastEx.makeText(getContext(), R.string.title_setup_done, Toast.LENGTH_LONG).show();
}