Example usage for android.content SharedPreferences getBoolean

List of usage examples for android.content SharedPreferences getBoolean

Introduction

In this page you can find the example usage for android.content SharedPreferences getBoolean.

Prototype

boolean getBoolean(String key, boolean defValue);

Source Link

Document

Retrieve a boolean value from the preferences.

Usage

From source file:com.github.vseguip.sweet.contacts.SweetContactSync.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Log.i(TAG, "onPerformSync()");
    // Get preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean fullSync = settings.getBoolean(mContext.getString(R.string.full_sync), false);
    if (fullSync)
        mAccountManager.setUserData(account, LAST_SYNC_KEY, null);
    performNetOperation(new SugarRunnable(account, syncResult, new ISugarRunnable() {
        @Override/*from  w  w  w.j  a va  2 s  . co  m*/
        public void run() throws URISyntaxException, OperationCanceledException, AuthenticatorException,
                IOException, AuthenticationException {
            Log.i(TAG, "Running PerformSync closure()");

            mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, true);
            SugarAPI sugar = SugarAPIFactory.getSugarAPI(mAccountManager, account);
            String lastDate = mAccountManager.getUserData(account, LAST_SYNC_KEY);
            List<ISweetContact> contacts = null;
            try {
                contacts = fetchContacts(sugar, lastDate);
            } catch (AuthenticationException ex) {
                // maybe expired session, invalidate token and request new
                // one
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            } catch (NullPointerException npe) {
                // maybe expired session, invalidate token and request new
                // one               
                mAccountManager.invalidateAuthToken(account.type, mAuthToken);
                mAuthToken = mAccountManager.blockingGetAuthToken(account, AUTH_TOKEN_TYPE, false);
            }
            // try again, it could be due to an expired session
            if (contacts == null) {
                contacts = fetchContacts(sugar, lastDate);
            }
            List<ISweetContact> modifiedContacts = ContactManager.getLocallyModifiedContacts(mContext, account);
            List<ISweetContact> createdContacts = ContactManager.getLocallyCreatedContacts(mContext, account);
            // Get latest date from server
            for (ISweetContact c : contacts) {
                String contactDate = c.getDateModified();
                if ((lastDate == null) || (lastDate.compareTo(contactDate) < 0)) {
                    lastDate = contactDate;
                }
            }
            // Determine conflicting contacts
            Set<String> conflictSet = getConflictSet(contacts, modifiedContacts);
            Map<String, ISweetContact> conflictingSugarContacts = filterIds(contacts, conflictSet);
            Map<String, ISweetContact> conflictingLocalContacts = filterIds(modifiedContacts, conflictSet);

            if (modifiedContacts.size() > 0) {
                // Send modified local non conflicting contacts to the
                // server
                List<String> newIds = sugar.sendNewContacts(mAuthToken, modifiedContacts, false);
                if (newIds.size() != modifiedContacts.size()) {
                    throw new OperationCanceledException("Error updating local contacts in the remote server");
                }
                ContactManager.cleanDirtyFlag(mContext, modifiedContacts);
            }
            if (createdContacts.size() > 0) {
                List<String> newIds = sugar.sendNewContacts(mAuthToken, createdContacts, true);
                if (newIds.size() != createdContacts.size()) {
                    // something wrong happened, it's probable the user will
                    // have to clear the data
                    throw new OperationCanceledException("Error creating local contacts in the remote server");
                }
                ContactManager.assignSourceIds(mContext, createdContacts, newIds);
                ContactManager.cleanDirtyFlag(mContext, createdContacts);
            }
            // Sync remote contacts locally.
            if (contacts.size() > 0) {
                ContactManager.syncContacts(mContext, account, contacts);
            }
            // resolve remaining conflicts
            List<ISweetContact> resolvedContacts = new ArrayList<ISweetContact>();
            for (String id : conflictSet) {
                ISweetContact local = conflictingLocalContacts.get(id);
                ISweetContact remote = conflictingSugarContacts.get(id);
                if (local.equals(remote)) {
                    // no need to sync
                    resolvedContacts.add(local);
                    conflictingLocalContacts.remove(id);
                    conflictingSugarContacts.remove(id);
                } else {
                    Log.i(TAG, "Local contact differs from remote contact " + local.getFirstName() + " "
                            + local.getLastName());
                    if (local.equalUIFields(remote)) {
                        // Differed in a non visible field like the account
                        // id or similar, use server version and resolve
                        // automatically
                        resolvedContacts.add(remote);
                        conflictingLocalContacts.remove(id);
                        conflictingSugarContacts.remove(id);
                    }
                }

            }
            ContactManager.cleanDirtyFlag(mContext, resolvedContacts);
            if (conflictingLocalContacts.size() > 0) {
                // Create a notification that can launch an mActivity to
                // resolve the pending conflict
                NotificationManager nm = (NotificationManager) mContext
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notify = new Notification(R.drawable.icon,
                        mContext.getString(R.string.notify_sync_conflict_ticket), System.currentTimeMillis());
                Intent intent = new Intent(mContext, SweetConflictResolveActivity.class);
                intent.putExtra("account", account);
                SweetConflictResolveActivity.storeConflicts(conflictingLocalContacts, conflictingSugarContacts);

                notify.setLatestEventInfo(mContext, mContext.getString(R.string.notify_sync_conflict_title),
                        mContext.getString(R.string.notify_sync_conflict_message),
                        PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
                nm.notify(SweetConflictResolveActivity.NOTIFY_CONFLICT,
                        SweetConflictResolveActivity.NOTIFY_CONTACT, notify);

                throw new OperationCanceledException("Pending conflicts");
            }
            // Save the last sync time in the account if all went ok
            mAccountManager.setUserData(account, LAST_SYNC_KEY, lastDate);
        }
    }));
}

From source file:com.acrutiapps.browser.ui.components.CustomWebView.java

@SuppressLint("SetJavaScriptEnabled")
public void loadSettings() {
    WebSettings settings = getSettings();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());

    settings.setJavaScriptEnabled(prefs.getBoolean(Constants.PREFERENCE_ENABLE_JAVASCRIPT, true));
    settings.setLoadsImagesAutomatically(prefs.getBoolean(Constants.PREFERENCE_ENABLE_IMAGES, true));
    settings.setUseWideViewPort(prefs.getBoolean(Constants.PREFERENCE_USE_WIDE_VIEWPORT, true));
    settings.setLoadWithOverviewMode(prefs.getBoolean(Constants.PREFERENCE_LOAD_WITH_OVERVIEW, false));

    settings.setGeolocationEnabled(prefs.getBoolean(Constants.PREFERENCE_ENABLE_GEOLOCATION, true));
    settings.setSaveFormData(prefs.getBoolean(Constants.PREFERENCE_REMEMBER_FORM_DATA, true));
    settings.setSavePassword(prefs.getBoolean(Constants.PREFERENCE_REMEMBER_PASSWORDS, true));

    settings.setTextZoom(prefs.getInt(Constants.PREFERENCE_TEXT_SCALING, 100));

    int minimumFontSize = prefs.getInt(Constants.PREFERENCE_MINIMUM_FONT_SIZE, 1);
    settings.setMinimumFontSize(minimumFontSize);
    settings.setMinimumLogicalFontSize(minimumFontSize);

    boolean useInvertedDisplay = prefs.getBoolean(Constants.PREFERENCE_INVERTED_DISPLAY, false);
    setWebSettingsProperty(settings, "inverted", useInvertedDisplay ? "true" : "false");

    if (useInvertedDisplay) {
        setWebSettingsProperty(settings, "inverted_contrast",
                Float.toString(prefs.getInt(Constants.PREFERENCE_INVERTED_DISPLAY_CONTRAST, 100) / 100f));
    }//  w w w .  j ava 2 s. co  m

    settings.setUserAgentString(prefs.getString(Constants.PREFERENCE_USER_AGENT, Constants.USER_AGENT_ANDROID));
    settings.setPluginState(PluginState
            .valueOf(prefs.getString(Constants.PREFERENCE_PLUGINS, PluginState.ON_DEMAND.toString())));

    CookieManager.getInstance().setAcceptCookie(prefs.getBoolean(Constants.PREFERENCE_ACCEPT_COOKIES, true));

    settings.setSupportZoom(true);
    settings.setDisplayZoomControls(false);
    settings.setBuiltInZoomControls(true);
    settings.setSupportMultipleWindows(true);
    settings.setEnableSmoothTransition(true);

    if (mPrivateBrowsing) {
        settings.setGeolocationEnabled(false);
        settings.setSaveFormData(false);
        settings.setSavePassword(false);

        settings.setAppCacheEnabled(false);
        settings.setDatabaseEnabled(false);
        settings.setDomStorageEnabled(false);
    } else {
        // HTML5 API flags
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);

        // HTML5 configuration settings.
        settings.setAppCacheMaxSize(3 * 1024 * 1024);
        settings.setAppCachePath(mContext.getDir("appcache", 0).getPath());
        settings.setDatabasePath(mContext.getDir("databases", 0).getPath());
        settings.setGeolocationDatabasePath(mContext.getDir("geolocation", 0).getPath());
    }

    setLongClickable(true);
    setDownloadListener(this);
}

From source file:de.ub0r.android.websms.connector.discotel.ConnectorDiscotel.java

/**
 * {@inheritDoc}/* w ww.  j  av a2  s. c om*/
 */
@Override
public final ConnectorSpec updateSpec(final Context context, final ConnectorSpec connectorSpec) {
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    if (p.getBoolean(Preferences.PREFS_ENABLED, false)) {
        if (p.getString(Preferences.PREFS_PASSWORD, "").length() > 0) {
            connectorSpec.setReady();
        } else {
            connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED);
        }
    } else {
        connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE);
    }
    return connectorSpec;
}

From source file:se.droidgiro.scanner.CaptureActivity.java

@Override
protected void onResume() {
    super.onResume();
    resetStatusView();//from  w w  w. j  a  v  a 2  s .c om

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
        // The activity was paused but not stopped, so the surface still
        // exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the
        // camera.
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    playBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
    if (playBeep) {
        // See if sound settings overrides this
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
    }
    vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
    initBeepSound();
}

From source file:com.quarterfull.newsAndroid.NewsReaderDetailFragment.java

@Override
public void onResume() {
    Log.v(TAG, "onResume called!");

    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

    mMarkAsReadWhileScrollingEnabled = mPrefs
            .getBoolean(SettingsActivity.CB_MARK_AS_READ_WHILE_SCROLLING_STRING, false);

    //When the fragment is instantiated by the xml file, onResume will be called twice
    if (onResumeCount >= 2) {
        RefreshCurrentRssView();//from   w w  w  .j av  a  2  s .com
    }
    onResumeCount++;

    super.onResume();
}

From source file:com.fairmichael.fintan.websms.connector.fishtext.ConnectorFishtext.java

@Override
public final ConnectorSpec updateSpec(final Context context, final ConnectorSpec connectorSpec) {
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    if (p.getBoolean(Preferences.PREFS_ENABLED, false)) {
        if (p.getString(Preferences.PREFS_PASSWORD, "").length() > 0) {
            connectorSpec.setReady();/*w ww  .  j a v  a2s.  co m*/
        } else {
            connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED);
        }
    } else {
        connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE);
    }
    return connectorSpec;
}

From source file:com.mercandalli.android.apps.files.user.LoginRegisterActivity.java

/**
 * Check if this is the first request to allow the {@link android.Manifest.permission#GET_ACCOUNTS} permission.
 *
 * @return Returns true if this is the very first request to allow {@link android.Manifest.permission#GET_ACCOUNTS} permission, false otherwise
 *///  w  w  w . j av a 2s .  co m
private boolean isFirstAccountPermissionRequest() {
    final SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_GET_ACCOUNT_PERMISSION,
            MODE_PRIVATE);
    return sharedPreferences.getBoolean(KEY_IS_FIRST_ACCOUNT_PERMISSION_REQUEST, true);
}

From source file:com.parking.billing.ParkingPayment.java

/**
 * If the database has not been initialized, we send a
 * RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items
 * for this user. This happens if the application has just been installed
 * or the user wiped data. We do not want to do this on every startup, rather, we want to do
 * only when the database needs to be initialized.
 *//*from  ww  w . ja  v a  2s.  co m*/
private void restoreDatabase() {
    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    boolean initialized = prefs.getBoolean(DB_INITIALIZED, false);
    if (!initialized) {
        mBillingService.restoreTransactions();
        Toast.makeText(this, R.string.restoring_transactions, Toast.LENGTH_LONG).show();
    }
}

From source file:ela.riskey.parammod.MainActivity.java

private boolean check() {
    final SharedPreferences prefs = this.getSharedPreferences("paramprefs", Context.MODE_PRIVATE);
    Boolean setuju = prefs.getBoolean("setuju", false);
    if (!setuju) {
        hDialog = new AlertDialog.Builder(MainActivity.this);
        hDialog.setTitle(R.string.app_name);
        hDialog.setMessage(R.string.falert);
        hDialog.setCancelable(false);//from w ww .  j av  a 2 s  .  c o  m
        hDialog.setPositiveButton(R.string.ya, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                try {
                    ShellInterface.setShell("sh");
                    String partisi = ShellInterface.getProcessOutput("mount | grep -i lfs | awk '{print $1}'");
                    String model = ShellInterface.getProcessOutput("getprop ro.product.model");
                    Log.e(getPackageName(), partisi);
                    Log.e(getPackageName(), model);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString("partisi", partisi);
                    editor.putString("model", model);
                    editor.putBoolean("setuju", true);
                    editor.commit();
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
            }
        });
        hDialog.setNegativeButton(R.string.tak, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        hDialog.create();
        hDialog.show();
    }
    return false;
}

From source file:com.nextgis.firereporter.ReporterService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Received start id " + startId + ": " + intent);
    super.onStartCommand(intent, flags, startId);

    if (intent == null)
        return START_STICKY;
    String action = intent.getAction();
    if (action.equals(ACTION_STOP)) {
        this.stopSelf();
    } else if (action.equals(ACTION_START)) {
        Log.d(TAG, "Action " + ACTION_START);
        Context c = this.getApplicationContext();
        SharedPreferences prefs = getSharedPreferences(MainActivity.PREFERENCES,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        long nMinTimeBetweenSend = prefs.getLong(SettingsActivity.KEY_PREF_INTERVAL + "_long",
                DateUtils.MINUTE_IN_MILLIS);
        boolean bBattEconomy = prefs.getBoolean(SettingsActivity.KEY_PREF_SERVICE_BATT_SAVE, true);

        if (!HttpGetter.IsNetworkAvailible(c)) {
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
            Log.d(TAG, "network not availible");
            return START_NOT_STICKY;
        }/*  w ww  .j av  a 2 s.c om*/

        Cursor cursor = ReportsDB.query(ReportsDatabase.TABLE_POS, null, null, null, null, null, null);
        Log.d(TAG, "record count = " + cursor.getCount());
        if (cursor.getCount() < 1) {
            this.stopSelf();
            return START_NOT_STICKY;
        }

        if (fireDataSender == null) {
            Log.d(TAG, "new fireDataSender");
            fireDataSender = new SendFireDataTask();
            fireDataSender.execute(this.getApplicationContext());
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
        } else if (fireDataSender.getStatus() == AsyncTask.Status.FINISHED) {
            Log.d(TAG, "exist fireDataSender");
            fireDataSender.execute(this.getApplicationContext());
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
        } else if (fireDataSender.getStatus() == AsyncTask.Status.PENDING
                || fireDataSender.getStatus() == AsyncTask.Status.RUNNING) {
            Log.d(TAG, "exist fireDataSender executing");
            ScheduleNextUpdate(c, nMinTimeBetweenSend, bBattEconomy);
        } else {
            Log.d(TAG, "unexpected behaviour");
            this.stopSelf();
        }
    }
    return START_NOT_STICKY;
}