List of usage examples for android.content SharedPreferences getStringSet
@Nullable Set<String> getStringSet(String key, @Nullable Set<String> defValues);
From source file:com.karma.konnect.PwoDiscoveryService.java
private void restoreCache() { // Make sure we are trying to load the right version of the cache String preferencesKey = getString(R.string.discovery_service_prefs_key); SharedPreferences prefs = getSharedPreferences(preferencesKey, Context.MODE_PRIVATE); int prefsVersion = prefs.getInt(PREFS_VERSION_KEY, 0); long now = new Date().getTime(); if (prefsVersion != PREFS_VERSION) { mScanStartTime = now;/*from www. j ava 2s . co m*/ return; } // Don't load the cache if it's stale mScanStartTime = prefs.getLong(SCAN_START_TIME_KEY, 0); if (now - mScanStartTime >= SCAN_STALE_TIME_MILLIS) { mScanStartTime = now; return; } // Restore the cached metadata Set<String> serializedPwoMetadata = prefs.getStringSet(PWO_METADATA_KEY, new HashSet<String>()); for (String pwoMetadataStr : serializedPwoMetadata) { PwoMetadata pwoMetadata; try { pwoMetadata = PwoMetadata.fromJsonStr(pwoMetadataStr); } catch (JSONException e) { Log.e(TAG, "Could not deserialize PWO cache item: " + e); continue; } onPwoDiscovered(pwoMetadata); if (pwoMetadata.hasBleMetadata()) { pwoMetadata.bleMetadata.updateRegionInfo(); } } }
From source file:org.chromium.chrome.browser.physicalweb.UrlManager.java
private void initSharedPreferences() { // Check the version. final SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); if (prefs.getInt(PREFS_VERSION_KEY, 0) != PREFS_VERSION) { new AsyncTask<Void, Void, Void>() { @Override//from w ww .ja v a 2s . co m protected Void doInBackground(Void... params) { prefs.edit().putInt(PREFS_VERSION_KEY, PREFS_VERSION) // This clean up code can be deleted in m57. .remove("physicalweb_resolved_urls").apply(); return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return; } // Read the cache. mNearbyUrls.addAll(prefs.getStringSet(PREFS_NEARBY_URLS_KEY, new HashSet<String>())); for (String serializedUrl : prefs.getStringSet(PREFS_ALL_URLS_KEY, new HashSet<String>())) { try { JSONObject jsonObject = new JSONObject(serializedUrl); UrlInfo urlInfo = UrlInfo.jsonDeserialize(jsonObject); mUrlInfoMap.put(urlInfo.getUrl(), urlInfo); mUrlsSortedByTimestamp.add(urlInfo.getUrl()); } catch (JSONException e) { Log.e(TAG, "Could not deserialize UrlInfo", e); } } for (String serializedPwsResult : prefs.getStringSet(PREFS_PWS_RESULTS_KEY, new HashSet<String>())) { try { JSONObject jsonObject = new JSONObject(serializedPwsResult); PwsResult pwsResult = PwsResult.jsonDeserialize(jsonObject); mPwsResultMap.put(pwsResult.requestUrl, pwsResult); } catch (JSONException e) { Log.e(TAG, "Could not deserialize PwsResult", e); } } garbageCollect(); }
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
@Override protected void readParameter() { GregorianCalendar gToday = new GregorianCalendar( TimeZone.getTimeZone(mContext.getResources().getString(R.string.my_time_zone_en))); SharedPreferences sharedPref = mContext.getSharedPreferences(MainActivity.package_name + ".profile", Context.MODE_PRIVATE); String param = sharedPref.getString(MainActivity.ONE_BOOT_PARAMS, "--"); Set<String> aSet = sharedPref.getStringSet(MainActivity.SET_ONE_BOOT, null); if (aSet == null) { last4 = -1;/*from ww w. ja v a2 s . c o m*/ return; } String[] allData = new String[aSet.size()]; allData = aSet.toArray(allData); String todayName = ScheduleActivity.weekDays[(gToday.get(Calendar.DAY_OF_WEEK) + 6) % 7];//ScheduleActivity.weekDays[gToday.get(Calendar.DAY_OF_WEEK)-1]; param = null; for (int i = 0; i < aSet.size(); i++) { if (allData[i].indexOf(todayName) < 0) continue; param = allData[i].replace('>', '-'); //saved data format change to weekdayName>HH:MM-last4 //data has form hh:mm-active period break; } if (param == null) { last4 = -1; return; } String[] terms = param.split("-"); int iH = Integer.parseInt(terms[1].substring(0, 2)); int iM = Integer.parseInt(terms[1].substring(3)); int iHr = gToday.get(Calendar.HOUR_OF_DAY); int iMin = gToday.get(Calendar.MINUTE); init_wait = ((iH - iHr) * 60 + (iM - iMin)) * 60 * 1000; //in milli secs on_time = 60 * 1000 * Integer.parseInt(terms[2]); //if (init_wait>0) last4 = on_time; if (init_wait < -1 * 60 * 1000) on_time = -1; //in milli secs //last4=init_wait+end_time; }
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
@Override protected void readParameter() { GregorianCalendar gToday = new GregorianCalendar( TimeZone.getTimeZone(mContext.getResources().getString(R.string.my_time_zone_en))); SharedPreferences sharedPref = mContext.getSharedPreferences(MainActivity.package_name + ".profile", Context.MODE_PRIVATE); String param = sharedPref.getString(MainActivity.N_BOOT_PARAMS, "--"); Set<String> aSet = sharedPref.getStringSet(MainActivity.SET_MULTIPLE_BOOT, null); if (aSet == null) { last4 = -1;/*w w w . j a v a 2 s.co m*/ return; } String[] allData = new String[aSet.size()]; allData = aSet.toArray(allData); String todayName = ScheduleActivity.weekDays[(gToday.get(Calendar.DAY_OF_WEEK) + 6) % 7]; String yesterday = ScheduleActivity.weekDays[(gToday.get(Calendar.DAY_OF_WEEK) + 5) % 7]; int hrNow = gToday.get(Calendar.HOUR_OF_DAY); param = null; for (int i = 0; i < aSet.size(); i++) { if (allData[i].indexOf(todayName) < 0) continue; param = allData[i].replace('>', '-'); //saved data format change to weekdayName>HH:MM-last4 //data has form hh:mm-active period break; } if (hrNow > 7 && param == null) { last4 = -1; return; } int hrBase = 0; String param0 = null; if (hrNow < 7) { if (param != null) { int idd = param.indexOf("-"); int h0 = Integer.parseInt(param.substring(idd + 1, idd + 3)); if (h0 > 7) param = null; } if (param == null) { for (int i = 0; i < aSet.size(); i++) { if (allData[i].indexOf(yesterday) < 0) continue; param = allData[i].replace('>', '-'); break; } if (param == null) { last4 = -1; return; } int idd = param.indexOf("-"); int h0 = Integer.parseInt(param.substring(idd + 1, idd + 3)); if (h0 < 21) { last4 = -1; return; } hrBase = 24; } } Log.i("SCHEDULE_JOB", "found parameters " + param + " as new schedule"); String[] terms = param.split("-"); int icx = terms[1].indexOf(":"); if (icx < 0) { last4 = -1; return; } int hrStart = Integer.parseInt(terms[1].substring(0, icx)); //starting hour int minStart = Integer.parseInt(terms[1].substring(icx + 1)); hrNow += hrBase; //int hrEnd=7+hrBase; int minNow = gToday.get(Calendar.MINUTE); on_time = 1000 * 60 * Integer.parseInt(terms[2]); //in milli secs off_time = 1000 * 3600 * Integer.parseInt(terms[3]); //in milli secs init_wait = ((hrStart - hrNow) * 60 + (minStart - minNow)) * 60 * 1000; //in milli secs while (init_wait < 0) { init_wait += (on_time + off_time); } //change the end time to 07:00AM //int endHr=7; // if (iH > 7) endHr=7+24; //end_time=((endHr-iH)*60+(0-iM))*60*1000; //end_time=1000*60*Integer.parseInt(terms[3]); //in milli secs //last4=init_wait+end_time; last4 = 1000; }
From source file:nl.mpcjanssen.simpletask.Simpletask.java
@NotNull public ArrayList<ActiveFilter> getSavedFilter() { ArrayList<ActiveFilter> saved_filters = new ArrayList<ActiveFilter>(); SharedPreferences saved_filter_ids = getSharedPreferences("filters", MODE_PRIVATE); Set<String> filterIds = saved_filter_ids.getStringSet("ids", new HashSet<String>()); for (String id : filterIds) { SharedPreferences filter_pref = getSharedPreferences(id, MODE_PRIVATE); ActiveFilter filter = new ActiveFilter(); filter.initFromPrefs(filter_pref); filter.setPrefName(id);//from w w w .java 2s. co m saved_filters.add(filter); } return saved_filters; }
From source file:nl.mpcjanssen.simpletask.Simpletask.java
private void deleteSavedFilter(String prefsName) { SharedPreferences saved_filters = getSharedPreferences("filters", MODE_PRIVATE); HashSet<String> ids = new HashSet<String>(); ids.addAll(saved_filters.getStringSet("ids", new HashSet<String>())); ids.remove(prefsName);/* ww w .j a va 2s.c om*/ saved_filters.edit().putStringSet("ids", ids).apply(); SharedPreferences filter_prefs = getSharedPreferences(prefsName, MODE_PRIVATE); ActiveFilter deleted_filter = new ActiveFilter(); deleted_filter.initFromPrefs(filter_prefs); filter_prefs.edit().clear().apply(); File prefs_path = new File(this.getFilesDir(), "../shared_prefs"); File prefs_xml = new File(prefs_path, prefsName + ".xml"); final boolean deleted = prefs_xml.delete(); if (!deleted) { Log.w(TAG, "Failed to delete saved filter: " + deleted_filter.getName()); } updateRightDrawer(); }
From source file:org.codarama.haxsync.services.ContactsSyncAdapterService.java
@SuppressWarnings("unused") private static void performSync(Context context, Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) throws OperationCanceledException { SharedPreferences prefs = context.getSharedPreferences(context.getPackageName() + "_preferences", MODE_MULTI_PROCESS);/*from w w w . j a v a 2 s .c om*/ mContentResolver = context.getContentResolver(); FacebookUtil.refreshPermissions(context); //TODO: Clean up stuff that isn't needed anymore since Graph API boolean cropPhotos = true; boolean sync = prefs.getBoolean("sync_status", true); boolean syncNew = prefs.getBoolean("status_new", true); boolean syncLocation = prefs.getBoolean("sync_location", true); boolean syncSelf = prefs.getBoolean("sync_self", false); boolean imageDefault = prefs.getBoolean("image_primary", true); boolean oldStatus = sync && (!syncNew || (Build.VERSION.SDK_INT < 15)); boolean faceDetect = true; boolean root = prefs.getBoolean("root_enabled", false); int rootSize = 512; if (FacebookUtil.authorize(context, account)) { HashMap<String, SyncEntry> localContacts = getLocalContacts(account); HashMap<String, Long> names = loadPhoneContacts(context); HashMap<String, Long> uids = loadHTCData(context); //Log.i("CONTACTS", names.toString()); boolean phoneOnly = prefs.getBoolean("phone_only", true); /*if (phoneOnly){ names = loadPhoneContacts(context); }*/ boolean wifiOnly = prefs.getBoolean("wifi_only", false); boolean syncEmail = prefs.getBoolean("sync_facebook_email", false); boolean syncBirthday = prefs.getBoolean("sync_contact_birthday", true); boolean force = prefs.getBoolean("force_dl", false); boolean google = prefs.getBoolean("update_google_photos", false); boolean ignoreMiddleaNames = prefs.getBoolean("ignore_middle_names", false); boolean addMeToFriends = prefs.getBoolean("add_me_to_friends", false); Log.i("google", String.valueOf(google)); int fuzziness = Integer.parseInt(prefs.getString("fuzziness", "2")); Set<String> addFriends = prefs.getStringSet("add_friends", new HashSet<String>()); Log.i(TAG, "phone_only: " + Boolean.toString(phoneOnly)); Log.i(TAG, "wifi_only: " + Boolean.toString(wifiOnly)); Log.i(TAG, "is wifi: " + Boolean.toString(DeviceUtil.isWifi(context))); Log.i(TAG, "phone contacts: " + names.toString()); Log.i(TAG, "using old status api: " + String.valueOf(oldStatus)); Log.i(TAG, "ignoring middle names : " + String.valueOf(ignoreMiddleaNames)); Log.i(TAG, "add me to friends : " + String.valueOf(addMeToFriends)); boolean chargingOnly = prefs.getBoolean("charging_only", false); int maxsize = BitmapUtil.getMaxSize(context.getContentResolver()); File cacheDir = context.getCacheDir(); Log.i("CACHE DIR", cacheDir.getAbsolutePath()); Log.i("MAX IMAGE SIZE", String.valueOf(maxsize)); if (!((wifiOnly && !DeviceUtil.isWifi(context)) || (chargingOnly && !DeviceUtil.isCharging(context)))) { try { if (syncSelf) { addSelfContact(account, maxsize, cropPhotos, faceDetect, force, root, rootSize, cacheDir, google); } List<FacebookGraphFriend> friends = FacebookUtil.getFriends(maxsize, addMeToFriends); for (FacebookGraphFriend friend : friends) { String uid = friend.getUserName(); String friendName = friend.getName(ignoreMiddleaNames); if (friendName != null && uid != null) { String match = matches(names.keySet(), friendName, fuzziness); if (!(phoneOnly && (match == null) && !uids.containsKey(uid)) || addFriends.contains(friendName)) { // STEP 1. Add contact - if the contact is not part of the HTCData records and does not match any // of the fuzziness names we add them to the list of contacts with the intention to make them available // for manual merge (I guess) if (localContacts.get(uid) == null) { //String name = friend.getString("name"); //Log.i(TAG, name + " already on phone: " + Boolean.toString(names.contains(name))); addContact(account, friendName, uid); SyncEntry entry = new SyncEntry(); Uri rawContactUr = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name) .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type) .appendQueryParameter(RawContacts.Data.DATA1, uid).build(); Cursor c = mContentResolver.query(rawContactUr, new String[] { BaseColumns._ID }, null, null, null); c.moveToLast(); long id = c.getLong(c.getColumnIndex(BaseColumns._ID)); c.close(); // Log.i("ID", Long.toString(id)); entry.raw_id = id; localContacts.put(uid, entry); if (uids.containsKey(uid)) { ContactUtil.merge(context, uids.get(uid), id); } else if (names.containsKey(match)) { ContactUtil.merge(context, names.get(match), id); } //localContacts = loadContacts(accounts, context); } // STEP 2. Set contact photo SyncEntry contact = localContacts.get(uid); updateContactPhoto(contact.raw_id, friend.getPicTimestamp(), maxsize, cropPhotos, friend.getPicURL(), faceDetect, force, root, rootSize, cacheDir, google, imageDefault); if (syncEmail && !FacebookUtil.RESPECT_FACEBOOK_POLICY) ContactUtil.addEmail(context, contact.raw_id, friend.getEmail()); if (syncLocation && !FacebookUtil.RESPECT_FACEBOOK_POLICY) { ContactUtil.updateContactLocation(contact.raw_id, friend.getLocation()); } if (oldStatus && !FacebookUtil.RESPECT_FACEBOOK_POLICY) { ArrayList<Status> statuses = friend.getStatuses(); if (statuses.size() >= 1) { updateContactStatus(contact.raw_id, statuses.get(0).getMessage(), statuses.get(0).getTimestamp()); } } if (syncBirthday && !FacebookUtil.RESPECT_FACEBOOK_POLICY) { String birthday = friend.getBirthday(); if (birthday != null) { ContactUtil.addBirthday(contact.raw_id, birthday); } } } } } } catch (Exception e) { // FIXME catching the generic Exception class is not hte best thing to do Log.e("ERROR", e.toString()); } if (root) { try { RootUtil.refreshContacts(); } catch (ShellException e) { Log.e("Error", e.getLocalizedMessage()); } } if (force) { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("force_dl", false); editor.commit(); } } else { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("missed_contact_sync", true); editor.commit(); } } }
From source file:nl.mpcjanssen.simpletask.Simpletask.java
/** * Handle add filter click *//from w w w. j a va 2 s . c o m */ public void onAddFilterClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(R.string.save_filter); alert.setMessage(R.string.save_filter_message); // Set an EditText view to get user input final EditText input = new EditText(this); alert.setView(input); input.setText(mFilter.getProposedName()); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable text = input.getText(); String value; if (text == null) { value = ""; } else { value = text.toString(); } if (value.equals("")) { Util.showToastShort(getApplicationContext(), R.string.filter_name_empty); } else { SharedPreferences saved_filters = getSharedPreferences("filters", MODE_PRIVATE); int newId = saved_filters.getInt("max_id", 1) + 1; Set<String> filters = saved_filters.getStringSet("ids", new HashSet<String>()); filters.add("filter_" + newId); saved_filters.edit().putStringSet("ids", filters).putInt("max_id", newId).apply(); SharedPreferences test_filter_prefs = getSharedPreferences("filter_" + newId, MODE_PRIVATE); mFilter.setName(value); mFilter.saveInPrefs(test_filter_prefs); updateRightDrawer(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); }
From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java
public String readBootParameter(int mode_1_n) { String retS = null;//from www . ja va 2s . com GregorianCalendar gToday = new GregorianCalendar( TimeZone.getTimeZone(getResources().getString(R.string.my_time_zone_en))); SharedPreferences sharedPref = getSharedPreferences(MainActivity.package_name + ".profile", Context.MODE_PRIVATE); String param = sharedPref.getString(MainActivity.ONE_BOOT_PARAMS, "--"); String paramKey = MainActivity.SET_MULTIPLE_BOOT; if (mode_1_n == 1) paramKey = MainActivity.SET_ONE_BOOT; Set<String> aSet = sharedPref.getStringSet(paramKey, null); if (aSet == null) { return null; } String[] allData = new String[aSet.size()]; allData = aSet.toArray(allData); String todayName = ScheduleActivity.weekDays[(gToday.get(Calendar.DAY_OF_WEEK) + 6) % 7];//ScheduleActivity.weekDays[gToday.get(Calendar.DAY_OF_WEEK)-1]; String scheduleDay = todayName; param = null; for (int i = 0; i < aSet.size(); i++) { if (allData[i].indexOf(scheduleDay) < 0) continue; param = allData[i].replace('>', '-'); //saved data format change to weekdayName>HH:MM-last4 //data has form hh:mm-active period break; } int hrNow = gToday.get(Calendar.HOUR_OF_DAY); if (param == null) { if (mode_1_n == 1 || hrNow > 7) return null; } if (mode_1_n != 1 && hrNow < 7) { if (param != null) { int idd = param.indexOf("-"); int h0 = Integer.parseInt(param.substring(idd + 1, idd + 3)); if (h0 > 7) param = null; } scheduleDay = ScheduleActivity.weekDays[(gToday.get(Calendar.DAY_OF_WEEK) + 5) % 7]; //check if scheduled yesterday if (param == null) { for (int i = 0; i < aSet.size(); i++) { if (allData[i].indexOf(scheduleDay) < 0) continue; param = allData[i].replace('>', '-'); break; } if (param == null) { return null; } int idd = param.indexOf("-"); int h0 = Integer.parseInt(param.substring(idd + 1, idd + 3)); if (h0 < 21) { return null; } hrNow += 24; //hrBase = 24; } } String[] terms = param.split("-"); int icx = terms[1].indexOf(":"); if (icx < 0) { Log.w("SCHEDULE_JOB", "!!! Bad formated start time " + param + " as new schedule"); return null; } int hrStart = Integer.parseInt(terms[1].substring(0, icx)); //starting hour int minStart = Integer.parseInt(terms[1].substring(icx + 1)); int minNow = gToday.get(Calendar.MINUTE); long init_wait = ((hrStart - hrNow) * 60 + (minStart - minNow)) * 60 * 1000; //in milli secs long on_time = 60 * 1000 * Integer.parseInt(terms[2]); //if (init_wait>0) if (mode_1_n == 1) { if (init_wait < -2 * 60 * 1000) return null; if (init_wait < 0) init_wait = 0; if (on_time < 1) return null; //if (init_wait >3605000) return null; retS = "" + init_wait + "-" + on_time; return retS; } long off_time = 1000 * 3600 * Integer.parseInt(terms[3]); //in milli secs while (init_wait < 0) { init_wait += off_time;//(on_time+off_time); } retS = "" + init_wait + "-" + on_time + "-" + off_time; return retS; }
From source file:eu.faircode.adblocker.ServiceSinkhole.java
private List<Rule> getAllowedRules(List<Rule> listRule) { List<Rule> listAllowed = new ArrayList<>(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Check state boolean wifi = Util.isWifiActive(this); boolean metered = Util.isMeteredNetwork(this); boolean useMetered = prefs.getBoolean("use_metered", false); Set<String> ssidHomes = prefs.getStringSet("wifi_homes", new HashSet<String>()); String ssidNetwork = Util.getWifiSSID(this); String generation = Util.getNetworkGeneration(this); boolean unmetered_2g = prefs.getBoolean("unmetered_2g", false); boolean unmetered_3g = prefs.getBoolean("unmetered_3g", false); boolean unmetered_4g = prefs.getBoolean("unmetered_4g", false); boolean roaming = Util.isRoaming(ServiceSinkhole.this); boolean national = prefs.getBoolean("national_roaming", false); boolean tethering = prefs.getBoolean("tethering", false); boolean filter = prefs.getBoolean("filter", false); // Update connected state last_connected = Util.isConnected(ServiceSinkhole.this); boolean org_metered = metered; boolean org_roaming = roaming; // Update metered state if (wifi && !useMetered) metered = false;/* ww w .j a va 2 s . c om*/ if (wifi && ssidHomes.size() > 0 && !(ssidHomes.contains(ssidNetwork) || ssidHomes.contains('"' + ssidNetwork + '"'))) { metered = true; Log.i(TAG, "!@home"); } if (unmetered_2g && "2G".equals(generation)) metered = false; if (unmetered_3g && "3G".equals(generation)) metered = false; if (unmetered_4g && "4G".equals(generation)) metered = false; last_metered = metered; // Update roaming state if (roaming && national) roaming = Util.isInternational(this); Log.i(TAG, "Get allowed" + " connected=" + last_connected + " wifi=" + wifi + " home=" + TextUtils.join(",", ssidHomes) + " network=" + ssidNetwork + " metered=" + metered + "/" + org_metered + " generation=" + generation + " roaming=" + roaming + "/" + org_roaming + " interactive=" + last_interactive + " tethering=" + tethering + " filter=" + filter); if (last_connected) for (Rule rule : listRule) { boolean blocked = (metered ? rule.other_blocked : rule.wifi_blocked); boolean screen = (metered ? rule.screen_other : rule.screen_wifi); if ((!blocked || (screen && last_interactive)) && (!metered || !(rule.roaming && roaming))) listAllowed.add(rule); } Log.i(TAG, "Allowed " + listAllowed.size() + " of " + listRule.size()); return listAllowed; }