Java Code Examples for androidx.preference.PreferenceManager#getDefaultSharedPreferences()

The following examples show how to use androidx.preference.PreferenceManager#getDefaultSharedPreferences() . 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: 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 2
Source File: Util.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
public static void setTheme(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean dark = prefs.getBoolean("dark_theme", false);
    String theme = prefs.getString("theme", "teal");
    if (theme.equals("teal"))
        context.setTheme(dark ? R.style.AppThemeTealDark : R.style.AppThemeTeal);
    else if (theme.equals("blue"))
        context.setTheme(dark ? R.style.AppThemeBlueDark : R.style.AppThemeBlue);
    else if (theme.equals("purple"))
        context.setTheme(dark ? R.style.AppThemePurpleDark : R.style.AppThemePurple);
    else if (theme.equals("amber"))
        context.setTheme(dark ? R.style.AppThemeAmberDark : R.style.AppThemeAmber);
    else if (theme.equals("orange"))
        context.setTheme(dark ? R.style.AppThemeOrangeDark : R.style.AppThemeOrange);
    else if (theme.equals("green"))
        context.setTheme(dark ? R.style.AppThemeGreenDark : R.style.AppThemeGreen);

    if (context instanceof Activity && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setTaskColor(context);
}
 
Example 3
Source File: AdapterNavAccount.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
AdapterNavAccount(Context context, LifecycleOwner owner) {
    this.context = context;
    this.owner = owner;
    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.getTimeInstance(context, SimpleDateFormat.SHORT);

    setHasStableIds(true);
}
 
Example 4
Source File: PreferencesCommonFragment.java    From InviZible with GNU General Public License v3.0 5 votes vote down vote up
private void allowTorTethering(List<String> torConf) {

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

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean isolateDestAddress = sharedPreferences.getBoolean("pref_tor_isolate_dest_address", false);
        boolean isolateDestPort = sharedPreferences.getBoolean("pref_tor_isolate_dest_port", false);

        String line;
        for (int i = 0; i < torConf.size(); i++) {
            line = torConf.get(i);
            if (line.contains("TransPort")) {
                line = "TransPort " + addIsolateFlags(torTransPort, allowTorTether, isolateDestAddress, isolateDestPort);
                torConf.set(i, line);
            } else if (line.contains("SOCKSPort")) {
                line = "SOCKSPort " + addIsolateFlags(torSocksPort, allowTorTether, isolateDestAddress, isolateDestPort);
                torConf.set(i, line);
            } else if (line.contains("HTTPTunnelPort")) {
                line = "HTTPTunnelPort " + addIsolateFlags(torHTTPTunnelPort, allowTorTether, isolateDestAddress, isolateDestPort);
                torConf.set(i, line);
            }
        }

        FileOperations.writeToTextFile(getActivity(), appDataDir + "/app_data/tor/tor.conf", torConf, "ignored");
    }
 
Example 5
Source File: ServiceTileSynchronize.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private void update() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enabled = prefs.getBoolean("enabled", true);
    Log.i("Update tile synchronize=" + enabled);

    Tile tile = getQsTile();
    if (tile != null) {
        tile.setState(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE);
        tile.setIcon(Icon.createWithResource(this,
                enabled ? R.drawable.baseline_sync_24 : R.drawable.baseline_sync_disabled_24));
        tile.updateTile();
    }
}
 
Example 6
Source File: ServiceSinkhole.java    From NetGuard with GNU General Public License v3.0 5 votes vote down vote up
public static void reload(String reason, Context context, boolean interactive) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.getBoolean("enabled", false)) {
        Intent intent = new Intent(context, ServiceSinkhole.class);
        intent.putExtra(EXTRA_COMMAND, Command.reload);
        intent.putExtra(EXTRA_REASON, reason);
        intent.putExtra(EXTRA_INTERACTIVE, interactive);
        ContextCompat.startForegroundService(context, intent);
    }
}
 
Example 7
Source File: Helper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static boolean isOpenKeychainInstalled(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String provider = prefs.getString("openpgp_provider", "org.sufficientlysecure.keychain");

    PackageManager pm = context.getPackageManager();
    Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT_2);
    intent.setPackage(provider);
    List<ResolveInfo> ris = pm.queryIntentServices(intent, 0);

    return (ris.size() > 0);
}
 
Example 8
Source File: ActivitySettings.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
private void xmlImport(InputStream in) throws IOException, SAXException, ParserConfigurationException {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);
    prefs.edit().putBoolean("enabled", false).apply();
    ServiceSinkhole.stop("import", this, false);

    XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    XmlImportHandler handler = new XmlImportHandler(this);
    reader.setContentHandler(handler);
    reader.parse(new InputSource(in));

    xmlImport(handler.application, prefs);
    xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE));
    xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE));
    xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE));
    xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE));
    xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE));
    xmlImport(handler.lockdown, getSharedPreferences("lockdown", Context.MODE_PRIVATE));
    xmlImport(handler.apply, getSharedPreferences("apply", Context.MODE_PRIVATE));
    xmlImport(handler.notify, getSharedPreferences("notify", Context.MODE_PRIVATE));
    xmlImport(handler.blocklist, getSharedPreferences(PREF_BLOCKLIST, Context.MODE_PRIVATE));

    // Reload blocklist
    AppBlocklistController.getInstance(this).loadSettings(this);

    // Upgrade imported settings
    ReceiverAutostart.upgrade(true, this);

    DatabaseHelper.clearCache();

    // Refresh UI
    prefs.edit().putBoolean("imported", true).apply();
    prefs.registerOnSharedPreferenceChangeListener(this);
}
 
Example 9
Source File: TopFragment.java    From InviZible with GNU General Public License v3.0 5 votes vote down vote up
public void checkUpdates() {

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

        SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean autoUpdate = spref.getBoolean("pref_fast_auto_update", true)
                && !appVersion.startsWith("l") && !appVersion.endsWith("p") && !appVersion.startsWith("f");
        if (autoUpdate) {
            boolean throughTorUpdate = spref.getBoolean("pref_fast through_tor_update", false);
            boolean torRunning = new PrefManager(getActivity()).getBoolPref("Tor Running");
            boolean torReady = new PrefManager(getActivity()).getBoolPref("Tor Ready");
            String lastUpdateResult = new PrefManager(getActivity()).getStrPref("LastUpdateResult");
            if (!throughTorUpdate || (torRunning && torReady)) {
                long updateTimeCurrent = System.currentTimeMillis();
                String updateTimeLastStr = new PrefManager(getActivity()).getStrPref("updateTimeLast");
                if (!updateTimeLastStr.isEmpty()) {
                    long updateTimeLast = Long.parseLong(updateTimeLastStr);
                    final int UPDATES_CHECK_INTERVAL_HOURS = 24;
                    int interval = 1000 * 60 * 60 * UPDATES_CHECK_INTERVAL_HOURS;
                    if ((updateTimeCurrent - updateTimeLast > interval)
                            || (lastUpdateResult.isEmpty() && ((updateTimeCurrent - updateTimeLast) > 300000))
                            || lastUpdateResult.equals(getString(R.string.update_check_warning_menu)))
                        checkNewVer();
                } else {
                    checkNewVer();
                }
            }
        }
    }
 
Example 10
Source File: MicroActivity.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	setTheme(sp.getString("pref_theme", "light"));
	super.onCreate(savedInstanceState);
	ContextHolder.setCurrentActivity(this);
	setContentView(R.layout.activity_micro);
	OverlayView overlayView = findViewById(R.id.vOverlay);
	layout = findViewById(R.id.displayable_container);
	toolbar = findViewById(R.id.toolbar);
	setSupportActionBar(toolbar);
	actionBarEnabled = sp.getBoolean("pref_actionbar_switch", false);
	statusBarEnabled = sp.getBoolean("pref_statusbar_switch", false);
	boolean wakelockEnabled = sp.getBoolean("pref_wakelock_switch", false);
	if (wakelockEnabled) {
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}
	Intent intent = getIntent();
	String appName = intent.getStringExtra(ConfigActivity.MIDLET_NAME_KEY);
	microLoader = new MicroLoader(this, appName);
	microLoader.init();
	microLoader.applyConfiguration();
	VirtualKeyboard vk = ContextHolder.getVk();
	if (vk != null) {
		vk.setView(overlayView);
		overlayView.addLayer(vk);
	}
	if (vk instanceof FixedKeyboard) {
		setOrientation(ORIENTATION_PORTRAIT);
	} else {
		int orientation = microLoader.getOrientation();
		setOrientation(orientation);
	}
	try {
		loadMIDlet();
	} catch (Exception e) {
		e.printStackTrace();
		showErrorDialog(e.toString());
	}
}
 
Example 11
Source File: FragmentAccounts.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle args = getArguments();
    settings = (args == null || args.getBoolean("settings", true));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    cards = prefs.getBoolean("cards", true);
}
 
Example 12
Source File: ServerUrlActivity.java    From mage-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onApi(boolean valid, Exception error) {
	if (valid) {
		// Clear the database
		final DaoStore daoStore = DaoStore.getInstance(getApplicationContext());
		if (!daoStore.isDatabaseEmpty()) {
			daoStore.resetDatabase();
		}

		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(getString(R.string.serverURLKey), serverUrlTextView.getText().toString()).apply();

		// finish this activity back to the login activity
		done();
	} else {
		apiStatusView.setVisibility(View.GONE);
		serverUrlForm.setVisibility(View.VISIBLE);
		serverUrlButton.setEnabled(true);

		String message = "Cannot connect to server.";
		if (error == null) {
			message = "Application is not compatible with server.";

			new AlertDialog.Builder(this)
					.setTitle("Compatibility Error")
					.setMessage("Your MAGE application is not compatibile with this server.  Please update your application or contact your MAGE administrator for support.")
					.setPositiveButton(android.R.string.ok, null)
					.create()
					.show();
		} else {
			if (error.getCause() != null) {
				message = error.getCause().getMessage();
			}
		}

		serverUrlLayout.setError(message);
	}
}
 
Example 13
Source File: NoteServerSyncHelper.java    From nextcloud-notes with GNU General Public License v3.0 5 votes vote down vote up
private NoteServerSyncHelper(NotesDatabase db) {
    this.db = db;
    this.context = db.getContext();
    this.syncOnlyOnWifiKey = context.getApplicationContext().getResources().getString(R.string.pref_key_wifi_only);

    // Registers BroadcastReceiver to track network connection changes.
    context.getApplicationContext().registerReceiver(networkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context.getApplicationContext());
    prefs.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
    syncOnlyOnWifi = prefs.getBoolean(syncOnlyOnWifiKey, false);

    updateNetworkStatus();
}
 
Example 14
Source File: TopFragment.java    From InviZible with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onResume() {

    super.onResume();

    if (getActivity() != null) {

        if (onActivityChangeListener != null && getActivity() instanceof MainActivity) {
            onActivityChangeListener.onActivityChange((MainActivity) getActivity());
        }

        SharedPreferences shPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        rootIsAvailableSaved = rootIsAvailable = new PrefManager(getActivity()).getBoolPref("rootIsAvailable");
        runModulesWithRoot = shPref.getBoolean("swUseModulesRoot", false);

        ModulesStatus.getInstance().setFixTTL(shPref.getBoolean("pref_common_fix_ttl", false));

        String operationMode = new PrefManager(getActivity()).getStrPref("OPERATION_MODE");

        if (!operationMode.isEmpty()) {
            mode = OperationMode.valueOf(operationMode);
            ModulesAux.switchModes(getActivity(), rootIsAvailable, runModulesWithRoot, mode);
        }

        if (!runModulesWithRoot && haveModulesSavedStateRunning() && !isModulesStarterServiceRunning()) {
            startModulesStarterServiceIfStoppedBySystem();
            Log.e(LOG_TAG, "ModulesService stopped by system!");
        } else {
            ModulesAux.speedupModulesStateLoopTimer(getActivity());
        }

        if (PathVars.isModulesInstalled(getActivity()) && appVersion.endsWith("p")) {
            checkAgreement();
        }
    }
}
 
Example 15
Source File: DonationSuggestionDialogFragment.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
public static void showIfNeeded(Context context, FragmentManager fragmentManager) {
    if (DefaultBillingManager.getInstance(context).getDonationStatus().getValue() == DonationStatus.DONATED)
        return;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (!prefs.getBoolean(KEY_SHOWN, false))
        new DonationSuggestionDialogFragment().show(fragmentManager, null);
}
 
Example 16
Source File: Config.java    From fresco with MIT License 4 votes vote down vote up
public static Config load(final Context context) {
  final SharedPreferences sharedPreferences =
      PreferenceManager.getDefaultSharedPreferences(context);
  return Builder.newBuilder()
      .setDataSourceType(
          sharedPreferences.getString(
              Const.DATA_SOURCE_KEY, context.getString(R.string.value_local_uri)))
      .setInfiniteDataSource(sharedPreferences.getBoolean(Const.INFINITE_DATA_SOURCE_KEY, false))
      .setDistinctUriDataSource(
          sharedPreferences.getBoolean(Const.DISTINCT_DATA_SOURCE_KEY, false))
      .setRecyclerLayoutType(
          sharedPreferences.getString(
              Const.RECYCLER_LAYOUT_KEY,
              context.getString(R.string.value_recyclerview_recycler_layout)))
      .setReuseOldController(sharedPreferences.getBoolean(Const.REUSE_OLD_CONTROLLER_KEY, false))
      .setUseRoundedCorners(sharedPreferences.getBoolean(Const.ROUNDED_CORNERS_KEY, false))
      .setUseRoundedAsCircle(sharedPreferences.getBoolean(Const.ROUNDED_AS_CIRCLE_KEY, false))
      .setUsePostprocessor(sharedPreferences.getBoolean(Const.USE_POSTPROCESSOR_KEY, false))
      .setPostprocessorType(
          sharedPreferences.getString(
              Const.POSTPROCESSOR_TYPE_KEY,
              context.getString(R.string.value_postprocessor_medium)))
      .setScaleType(
          sharedPreferences.getString(
              Const.SCALE_TYPE_KEY, context.getString(R.string.value_scale_type_fit_center)))
      .setRotateUsingMetaData(sharedPreferences.getBoolean(Const.AUTO_ROTATE_KEY, false))
      .setForcedRotationAngle(
          Integer.parseInt(sharedPreferences.getString(Const.FORCED_ROTATION_ANGLE_KEY, "0")))
      .setDownsampling(sharedPreferences.getBoolean(Const.DOWNSAMPLING_KEY, false))
      .setOverrideSize(sharedPreferences.getBoolean(Const.OVERRIDE_SIZE_KEY, false))
      .setOverridenWidth(
          sharedPreferences.getInt(Const.OVERRIDEN_WIDTH_KEY, SizeUtil.DISPLAY_WIDTH / 2))
      .setOverridenHeight(
          sharedPreferences.getInt(Const.OVERRIDEN_HEIGHT_KEY, SizeUtil.DISPLAY_HEIGHT / 2))
      .setFadeDurationMs(
          Integer.parseInt(
              sharedPreferences.getString(
                  Const.FADE_DURATION_KEY, context.getString(R.string.value_fast_fade_duration))))
      .setDrawBorder(sharedPreferences.getBoolean(Const.DRAW_BORDER_KEY, false))
      .setGridSpanCount(
          Integer.parseInt(sharedPreferences.getString(Const.GRID_SPAN_COUNT_KEY, "3")))
      .setDecodeCancellation(sharedPreferences.getBoolean(Const.DECODE_CANCELLATION_KEY, false))
      .setWebpSupportEnabled(sharedPreferences.getBoolean(Const.WEBP_SUPPORT_KEY, false))
      .setDraweeOverlayEnabled(sharedPreferences.getBoolean(Const.DRAWEE_OVERLAY_KEY, false))
      .setInstrumentationEnabled(
          sharedPreferences.getBoolean(Const.INSTRUMENTATION_ENABLED_KEY, false))
      .setDecodingThreadCount(
          Integer.parseInt(sharedPreferences.getString(Const.DECODING_THREAD_KEY, "0")))
      .setBgColor(Integer.parseInt(sharedPreferences.getString(Const.BG_COLOR_KEY, "0")))
      .build();
}
 
Example 17
Source File: Migration_15_16.java    From nextcloud-notes with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Moves note list widget preferences from {@link SharedPreferences} to database
 * https://github.com/stefan-niedermann/nextcloud-notes/issues/832
 */
public Migration_15_16(SQLiteDatabase db, @NonNull Context context, @NonNull Runnable notifyWidgets) {
    db.execSQL("CREATE TABLE WIDGET_NOTE_LISTS ( " +
            "ID INTEGER PRIMARY KEY, " +
            "ACCOUNT_ID INTEGER, " +
            "CATEGORY_ID INTEGER, " +
            "MODE INTEGER NOT NULL, " +
            "THEME_MODE INTEGER NOT NULL, " +
            "FOREIGN KEY(ACCOUNT_ID) REFERENCES ACCOUNTS(ID), " +
            "FOREIGN KEY(CATEGORY_ID) REFERENCES CATEGORIES(CATEGORY_ID))");

    final String SP_WIDGET_KEY = "NLW_mode";
    final String SP_ACCOUNT_ID_KEY = "NLW_account";
    final String SP_DARK_THEME_KEY = "NLW_darkTheme";
    final String SP_CATEGORY_KEY = "NLW_cat";

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Map<String, ?> prefs = sharedPreferences.getAll();
    for (Map.Entry<String, ?> pref : prefs.entrySet()) {
        final String key = pref.getKey();
        Integer widgetId = null;
        Integer mode = null;
        Long accountId = null;
        Integer themeMode = null;
        Integer categoryId = null;
        if (key != null && key.startsWith(SP_WIDGET_KEY)) {
            try {
                widgetId = Integer.parseInt(key.substring(SP_WIDGET_KEY.length()));
                mode = (Integer) pref.getValue();
                accountId = sharedPreferences.getLong(SP_ACCOUNT_ID_KEY + widgetId, -1);

                try {
                    themeMode = DarkModeSetting.valueOf(sharedPreferences.getString(SP_DARK_THEME_KEY + widgetId, DarkModeSetting.SYSTEM_DEFAULT.name())).getModeId();
                } catch (ClassCastException e) {
                    //DARK_THEME was a boolean in older versions of the app. We thereofre have to still support the old setting.
                    themeMode = sharedPreferences.getBoolean(SP_DARK_THEME_KEY + widgetId, false) ? DarkModeSetting.DARK.getModeId() : DarkModeSetting.LIGHT.getModeId();
                }

                if (mode == 2) {
                    final String categoryTitle = sharedPreferences.getString(SP_CATEGORY_KEY + widgetId, null);
                    Cursor cursor = db.query(
                            "CATEGORIES",
                            new String[]{"CATEGORY_ID"},
                            "CATEGORY_TITLE = ? AND CATEGORY_ACCOUNT_ID = ? ",
                            new String[]{categoryTitle, String.valueOf(accountId)},
                            null,
                            null,
                            null);
                    if (cursor.moveToNext()) {
                        categoryId = cursor.getInt(0);
                    } else {
                        throw new IllegalStateException("No category id found for title \"" + categoryTitle + "\"");
                    }
                    cursor.close();
                }

                ContentValues migratedWidgetValues = new ContentValues();
                migratedWidgetValues.put("ID", widgetId);
                migratedWidgetValues.put("ACCOUNT_ID", accountId);
                migratedWidgetValues.put("CATEGORY_ID", categoryId);
                migratedWidgetValues.put("MODE", mode);
                migratedWidgetValues.put("THEME_MODE", themeMode);
                db.insert("WIDGET_NOTE_LISTS", null, migratedWidgetValues);
            } catch (Throwable t) {
                Log.e(TAG, "Could not migrate widget {widgetId: " + widgetId + ", accountId: " + accountId + ", mode: " + mode + ", categoryId: " + categoryId + ", themeMode: " + themeMode + "}");
                t.printStackTrace();
            } finally {
                // Clean up old shared preferences
                editor.remove(SP_WIDGET_KEY + widgetId);
                editor.remove(SP_CATEGORY_KEY + widgetId);
                editor.remove(SP_DARK_THEME_KEY + widgetId);
                editor.remove(SP_ACCOUNT_ID_KEY + widgetId);
            }
        }
    }
    editor.apply();
    notifyWidgets.run();
}
 
Example 18
Source File: MainActivity.java    From itag with GNU General Public License v3.0 4 votes vote down vote up
public void onWaytoday(@NonNull View sender) {
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    String tid = sp.getString("tid", "");
    boolean on = sp.getBoolean("wt", false);
    boolean first = sp.getBoolean("wtfirst", true);
    int freq = sp.getInt("freq", -1);
    final PopupMenu popupMenu = new PopupMenu(this, sender);
    popupMenu.inflate(R.menu.waytoday);
    popupMenu.getMenu().findItem(R.id.wt_about_first).setVisible(first);
    popupMenu.getMenu().findItem(R.id.wt_sec_1).setChecked(on && freq == 1);
    popupMenu.getMenu().findItem(R.id.wt_min_5).setChecked(on && freq == 300000);
    popupMenu.getMenu().findItem(R.id.wt_hour_1).setChecked(on && freq == 3600000);
    popupMenu.getMenu().findItem(R.id.wt_off).setVisible(on);
    popupMenu.getMenu().findItem(R.id.wt_new_tid).setVisible(!("".equals(tid) && first));
    popupMenu.getMenu().findItem(R.id.wt_about).setVisible(!first);
    popupMenu.getMenu().findItem(R.id.wt_share).setVisible(!"".equals(tid));
    popupMenu.setOnMenuItemClickListener(item -> {
        AlertDialog.Builder builder;
        switch (item.getItemId()) {
            case R.id.wt_sec_1:
                Waytoday.start(1);
                ITagApplication.faWtOn1();
                break;
            case R.id.wt_min_5:
                Waytoday.start(300000);
                break;
            case R.id.wt_hour_1:
                Waytoday.start(3600000);
                ITagApplication.faWtOn300();
                break;
            case R.id.wt_off:
                Waytoday.stop();
                ITagApplication.faWtOff();
                break;
            case R.id.wt_new_tid:
                ITagApplication.faWtChangeID();
                IDService.enqueueRetrieveId(this);
                break;
            case R.id.wt_share:
                ITagApplication.faWtShare();
                if (!"".equals(tid)) {
                    String txt = String.format(getResources().getString(R.string.share_link), tid);
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, txt);
                    sendIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share_subj));
                    // sendIntent.setType("message/rfc822");
                    sendIntent.setType("text/plain");
                    startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_title)));
                }
                break;
            case R.id.wt_about_first:
            case R.id.wt_about:
                ITagApplication.faWtAbout();
                builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.about_wt)
                        .setMessage(R.string.about_message)
                        .setPositiveButton(R.string.about_ok, (dialog, id) -> {
                            ITagApplication.faWtPlaymarket();
                            final String appPackageName = "s4y.waytoday";
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                            } catch (ActivityNotFoundException anfe) {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                            }
                        })
                        .setNegativeButton(R.string.about_cancel, (dialog, id) -> {
                            // User cancelled the dialog
                        });
                // Create the AlertDialog object and return it
                builder.create().show();
                break;
            case R.id.wt_disable:
                builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.disable_wt_ok)
                        .setMessage(R.string.disable_wt_msg)
                        .setPositiveButton(R.string.disable_wt_ok, (dialog, id) -> {
                            ITagApplication.faWtRemove();
                            // iTagsService.stopWayToday();
                            sp.edit().putBoolean("wt_disabled", true).apply();
                            final View v = findViewById(R.id.btn_waytoday);
                            if (v != null) {
                                v.setVisibility(View.GONE);
                            }
                        })
                        .setNegativeButton(R.string.about_cancel, (dialog, id) -> {
                            // User cancelled the dialog
                        });
                // Create the AlertDialog object and return it
                builder.create().show();
                break;
        }
        return true;
    });
    popupMenu.show();
}
 
Example 19
Source File: PixivArtProvider.java    From PixivforMuzei3 with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void onCommand(@NonNull Artwork artwork, int id) {
    @Nullable final Context context = getContext();
    Handler handler = new Handler(Looper.getMainLooper());
    switch (id) {
        case COMMAND_ADD_TO_BOOKMARKS:
            Log.d("PIXIV_DEBUG", "addToBookmarks(): Entered");
            if (context == null) {
                break;
            }
            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            if (sharedPrefs.getString(PREFERENCE_PIXIV_ACCESS_TOKEN, "").isEmpty()) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(context, R.string.toast_loginFirst, Toast.LENGTH_SHORT).show());
                return;
            }

            String accessToken;
            try {
                accessToken = PixivMuzeiSupervisor.INSTANCE.getAccessToken();
            } catch (AccessTokenAcquisitionException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(context, R.string.toast_loginFirst, Toast.LENGTH_SHORT).show());
                return;
            }
            sendPostRequest(accessToken, artwork.getToken());
            Log.d("PIXIV_DEBUG", "Added to bookmarks");
            handler.post(() ->
                    Toast.makeText(context, R.string.toast_addingToBookmarks, Toast.LENGTH_SHORT).show());
            break;
        case COMMAND_VIEW_IMAGE_DETAILS:
            if (context == null) {
                break;
            }
            String token = artwork.getToken();
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + token));
            IntentUtils.launchActivity(context, intent);
            break;
        case COMMAND_SHARE_IMAGE:
            Log.d("ANTONY_WORKER", "Opening sharing ");
            if (context == null) {
                break;
            }
            File newFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
                    artwork.getToken() + ".png");
            Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", newFile);
            Intent sharingIntent = new Intent();
            sharingIntent.setAction(Intent.ACTION_SEND);
            sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
            sharingIntent.setType("image/jpg");
            IntentUtils.launchActivity(context, sharingIntent);
        default:
    }
}
 
Example 20
Source File: Log.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
static void setup(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    debug = prefs.getBoolean("debug", false);

    setupBugsnag(context);
}