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.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;/*w ww .j  ava2s.c o m*/
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:com.tagaugmentedreality.utilties.Utilities.java

public static Object getSharedPreferences(Context context, String key, char type) {
    /**//from  ww w  . j a  v a  2  s  .  c  om
     * s: String i: Integer b: Boolean l: Long f: Float
     */

    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);

    if ('s' == type) {
        return (Object) settings.getString(key, "");
    } // end if
    else if ('i' == type) {
        return (Object) settings.getInt(key, 0);

    } // end else if
    else if ('b' == type) {
        return (Object) settings.getBoolean(key, false);
    } // end else if
    else if ('l' == type) {
        return (Object) settings.getLong(key, 0);

    } // end else if
    else if ('f' == type) {
        return (Object) settings.getFloat(key, 0.0f);

    } // end else if
    else {
        return null;
    } // end else

}

From source file:com.csipsimple.utils.PreferencesWrapper.java

private static Boolean gPrefBooleanValue(SharedPreferences aPrefs, String key) {
    if (BOOLEAN_PREFS.containsKey(key)) {
        return aPrefs.getBoolean(key, BOOLEAN_PREFS.get(key));
    }//from  w ww  .j  a v  a2 s.co  m
    return aPrefs.getBoolean(key, (Boolean) null);
}

From source file:be.deadba.ampd.SettingsActivity.java

/**
 * Binds a preference's summary to its value. More specifically, when the
 * preference's value is changed, its summary (line of text below the
 * preference title) is updated to reflect the value. The summary is also
 * immediately updated upon calling this method. The exact display format is
 * dependent on the type of preference.//w ww. java2s . co  m
 *
 * @see #sBindPreferenceSummaryToValueListener
 */
private static void bindPreferenceSummaryToValue(Preference preference,
        Preference.OnPreferenceChangeListener listener) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(listener);

    // Trigger the listener immediately with the preference's
    // current value.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(preference.getContext());
    String key = preference.getKey();
    Object value = preference instanceof TwoStatePreference ? Boolean.valueOf(sp.getBoolean(key, false))
            : sp.getString(key, "");

    listener.onPreferenceChange(preference, value);
}

From source file:com.zegoggles.smssync.PrefStore.java

static boolean upgradeCredentials(Context ctx) {
    final String flag = "upgraded_credentials";
    SharedPreferences prefs = getPrefs(ctx);

    boolean upgraded = prefs.getBoolean(flag, false);
    if (!upgraded) {
        Log.d(TAG, "Upgrading credentials");

        SharedPreferences creds = getCredentials(ctx);
        SharedPreferences.Editor prefsEditor = prefs.edit();
        SharedPreferences.Editor credsEditor = creds.edit();

        for (String field : new String[] { PREF_OAUTH_TOKEN, PREF_OAUTH_TOKEN_SECRET, PREF_LOGIN_PASSWORD }) {

            if (prefs.getString(field, null) != null && creds.getString(field, null) == null) {
                if (LOCAL_LOGV)
                    Log.v(TAG, "Moving credential " + field);
                credsEditor.putString(field, prefs.getString(field, null));
                prefsEditor.remove(field);
            } else if (LOCAL_LOGV)
                Log.v(TAG, "Skipping field " + field);
        }//from  w  w w. j  av  a  2  s.  co m
        boolean success = false;
        if (credsEditor.commit()) {
            prefsEditor.putBoolean(flag, true);
            success = prefsEditor.commit();
        }
        return success;
    } else {
        return false;
    }
}

From source file:net.sourceforge.kalimbaradio.androidapp.util.Util.java

public static void registerMediaButtonEventReceiver(Context context) {

    // Only do it if enabled in the settings.
    SharedPreferences prefs = getPreferences(context);
    boolean enabled = prefs.getBoolean(Constants.PREFERENCES_KEY_MEDIA_BUTTONS, true);

    if (enabled) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        ComponentName mediaButtonIntentReceiver = new ComponentName(context.getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        audioManager.registerMediaButtonEventReceiver(mediaButtonIntentReceiver);
    }/*  w  ww  . jav  a 2 s  .c o  m*/
}

From source file:com.fusionx.lightirc.util.SharedPreferencesUtils.java

private static ServerConfiguration.Builder convertPrefsToBuilder(final Context context, final String filename) {
    final SharedPreferences serverSettings = context.getSharedPreferences(filename, MODE_PRIVATE);
    final ServerConfiguration.Builder builder = new ServerConfiguration.Builder();

    // Server connection
    builder.setTitle(serverSettings.getString(PreferenceConstants.PREF_TITLE, ""));
    builder.setUrl(serverSettings.getString(PreferenceConstants.PREF_URL, "").trim());
    builder.setPort(Integer.parseInt(serverSettings.getString(PreferenceConstants.PREF_PORT, "6667")));

    // SSL// w  ww  . j  av a 2 s  .  co m
    builder.setSsl(serverSettings.getBoolean(PreferenceConstants.PREF_SSL, false));
    builder.setSslAcceptAllCertificates(
            serverSettings.getBoolean(PreferenceConstants.PREF_SSL_ACCEPT_ALL_CONNECTIONS, false));

    // User settings
    final String firstChoice = serverSettings.getString(PreferenceConstants.PREF_NICK, "HoloIRCUser");
    final String secondChoice = serverSettings.getString(PreferenceConstants.PREF_SECOND_NICK, "");
    final String thirdChoice = serverSettings.getString(PreferenceConstants.PREF_THIRD_NICK, "");
    final NickStorage nickStorage = new NickStorage(firstChoice, secondChoice, thirdChoice);
    builder.setNickStorage(nickStorage);
    builder.setRealName(serverSettings.getString(PreferenceConstants.PREF_REALNAME, "HoloIRC"));
    builder.setNickChangeable(serverSettings.getBoolean(PreferenceConstants.PREF_AUTO_NICK, true));

    // Autojoin channels
    final ArrayList<String> auto = new ArrayList<String>(
            serverSettings.getStringSet(PreferenceConstants.PREF_AUTOJOIN, new HashSet<String>()));
    for (final String channel : auto) {
        builder.getAutoJoinChannels().add(channel);
    }

    // Server authorisation
    builder.setServerUserName(serverSettings.getString(PreferenceConstants.PREF_LOGIN_USERNAME, "holoirc"));
    builder.setServerPassword(serverSettings.getString(PreferenceConstants.PREF_LOGIN_PASSWORD, ""));

    // SASL authorisation
    builder.setSaslUsername(serverSettings.getString(PreferenceConstants.PREF_SASL_USERNAME, ""));
    builder.setSaslPassword(serverSettings.getString(PreferenceConstants.PREF_SASL_PASSWORD, ""));

    // NickServ authorisation
    builder.setNickservPassword(serverSettings.getString(PreferenceConstants.PREF_NICKSERV_PASSWORD, ""));
    return builder;
}

From source file:com.facebook.Settings.java

/**
 * Gets whether data such as that generated through AppEventsLogger and sent to Facebook should be restricted from
 * being used for purposes other than analytics and conversions, such as for targeting ads to this user.  Defaults
 * to false.  This value is stored on the device and persists across app launches.
 *
 * @param context   Used to read the value.
 *//*from  w ww  . j a  va2s .  c  om*/
public static boolean getLimitEventAndDataUsage(Context context) {
    SharedPreferences preferences = context.getSharedPreferences(AppEventsLogger.APP_EVENT_PREFERENCES,
            Context.MODE_PRIVATE);
    return preferences.getBoolean("limitEventUsage", false);
}

From source file:com.jbsoft.farmtotable.FarmToTableActivity.java

private static void getPreferences(SharedPreferences sharedPrefs) {
    if (sharedPrefs.getBoolean("FMART", true)) {
        NOFM = true;/*from   ww  w .  j a  va2 s  .c om*/
    }
    if (sharedPrefs.getBoolean("OFARM", true)) {
        NOFS = true;
    }
    if (sharedPrefs.getBoolean("VREST", true)) {
        NOVR = true;
    }
    if (sharedPrefs.getBoolean("OREST", true)) {
        NOOR = true;
    }
    if (sharedPrefs.getBoolean("COPEN", true)) {
        COPN = true;
    }

}

From source file:net.mceoin.cominghome.NestUtils.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the main Activity.
 *
 * @param transitionType The type of transition that occurred.
 *//*from  ww w . j  a v a2  s  .  c  om*/
public static void sendNotification(Context context, String transitionType) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean notifications = prefs.getBoolean(MainActivity.PREFS_NOTIFICATIONS, true);

    if (!notifications) {
        if (debug)
            Log.d(TAG, "notifications are turned off");
        return;
    }

    // Create an explicit content Intent that starts the main Activity
    Intent notificationIntent = new Intent(context, MainActivity.class);

    // Construct a task stack
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    // Adds the main Activity to the task stack as the parent
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Set the notification contents
    builder.setSmallIcon(R.drawable.home)
            .setContentTitle(context.getString(R.string.nest_transition_notification_title, transitionType))
            .setContentText(context.getString(R.string.nest_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}