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.raspi.chatapp.util.Notification.java

public void createNotification(String buddyId, String name, String message, String type) {
    SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    if (defaultSharedPreferences
            .getBoolean(context.getResources().getString(R.string.pref_key_new_message_notifications), true)) {
        int index = buddyId.indexOf("@");
        if (index != -1)
            buddyId = buddyId.substring(0, index);
        if (name == null)
            name = buddyId;//from   w w  w  . j a  va 2s  .c o m
        Log.d("DEBUG", "creating notification: " + buddyId + "|" + name + "|" + message);
        Intent resultIntent = new Intent(context, ChatActivity.class);
        resultIntent.setAction(NOTIFICATION_CLICK);
        String oldBuddyId = getOldBuddyId();
        Log.d("DEBUG",
                (oldBuddyId == null) ? ("oldBuddy is null (later " + buddyId) : ("oldBuddy: " + oldBuddyId));
        if (oldBuddyId == null || oldBuddyId.equals("")) {
            oldBuddyId = buddyId;
            setOldBuddyId(buddyId);
        }
        if (oldBuddyId.equals(buddyId)) {
            resultIntent.putExtra(Constants.BUDDY_ID, buddyId);
            resultIntent.putExtra(Constants.CHAT_NAME, name);
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(ChatActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager nm = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
        NotificationCompat.Style style;

        String[] previousNotifications = readJSONArray(CURRENT_NOTIFICATIONS);
        String title;
        String[] currentNotifications = Arrays.copyOf(previousNotifications, previousNotifications.length + 1);
        currentNotifications[currentNotifications.length - 1] = name + ": " + message;
        if (previousNotifications.length == 0) {
            style = new NotificationCompat.BigTextStyle();
            NotificationCompat.BigTextStyle bigTextStyle = ((NotificationCompat.BigTextStyle) style);
            title = context.getResources().getString(R.string.new_message) + " "
                    + context.getResources().getString(R.string.from) + " " + name;
            bigTextStyle.bigText(currentNotifications[0]);
            bigTextStyle.setBigContentTitle(title);
        } else {
            style = new NotificationCompat.InboxStyle();
            NotificationCompat.InboxStyle inboxStyle = (NotificationCompat.InboxStyle) style;
            title = (previousNotifications.length + 1) + " "
                    + context.getResources().getString(R.string.new_messages);
            for (String s : currentNotifications)
                if (s != null && !"".equals(s))
                    inboxStyle.addLine(s);
            inboxStyle.setSummaryText(
                    (currentNotifications.length > 2) ? ("+" + (currentNotifications.length - 2) + " more")
                            : null);
            inboxStyle.setBigContentTitle(title);
        }
        writeJSONArray(currentNotifications, CURRENT_NOTIFICATIONS);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
                .setContentText(currentNotifications[currentNotifications.length - 1])
                .setSmallIcon(MessageHistory.TYPE_TEXT.equals(type) ? R.drawable.ic_forum_white_48dp
                        : R.drawable.ic_photo_camera_white_48dp)
                .setLargeIcon(getLargeIcon(Character.toUpperCase(name.toCharArray()[0]))).setStyle(style)
                .setAutoCancel(true).setPriority(5).setContentIntent(resultPendingIntent);

        String str = context.getResources().getString(R.string.pref_key_privacy);
        mBuilder.setVisibility(context.getResources().getString(R.string.pref_value1_privacy).equals(str)
                ? NotificationCompat.VISIBILITY_SECRET
                : context.getResources().getString(R.string.pref_value2_privacy).equals(str)
                        ? NotificationCompat.VISIBILITY_PRIVATE
                        : NotificationCompat.VISIBILITY_PUBLIC);

        str = context.getResources().getString(R.string.pref_key_vibrate);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setVibrate(new long[] { 800, 500, 800, 500 });

        str = context.getResources().getString(R.string.pref_key_led);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setLights(Color.BLUE, 500, 500);

        str = defaultSharedPreferences.getString(context.getResources().getString(R.string.pref_key_ringtone),
                "");
        mBuilder.setSound("".equals(str) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                : Uri.parse(str));

        nm.notify(NOTIFICATION_ID, mBuilder.build());
        str = context.getResources().getString(R.string.pref_key_banner);
        if (!defaultSharedPreferences.getBoolean(str, true)) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
            }
            reset();
        }
    }
}

From source file:de.ub0r.android.websms.connector.innosend.ConnectorInnosend.java

/**
 * {@inheritDoc}//  w  ww  .j  av a  2  s  .  c om
 */
@Override
protected final void doUpdate(final Context context, final Intent intent) throws IOException {
    final ConnectorCommand c = new ConnectorCommand(intent);
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    if (!p.getBoolean(PREFS_HIDE_TYPE3, false) || !p.getBoolean(PREFS_HIDE_WO_SENDER, false)
            || !p.getBoolean(PREFS_HIDE_W_SENDER, false)) {
        this.sendData(context, c, false);
    }
    if (!p.getBoolean(PREFS_HIDE_FREE, false)) {
        this.sendData(context, c, true);
    }
}

From source file:gcm.play.android.samples.com.gcmquickstart.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();/* www .j  a v a  2s. co m*/

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    btnIniciarSesion = (Button) findViewById(R.id.btnIniciarSesion);
    cbRecordar = (CheckBox) findViewById(R.id.cbRecordar);

    progressDialog = new ProgressDialog(this, R.style.MyTheme);

    //Se establece como usuario la cuenta registrada por el usuario para que haga su inicio de sesin
    userName = UserData.getUserAccount(this);
    Log.d("USER_ACCOUNT_LOCAL", userName);
    etUsername.setText(userName);

    //Establece como no editable el edit text de Usuario
    etUsername.setKeyListener(null);

    //progressDialog = new ProgressDialog(this, R.style.MyTheme);
    progressDialog.setTitle("Registration ID");
    progressDialog.setMessage("Espere un momento...");
    progressDialog.setCancelable(false);
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.show();
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            progressDialog.dismiss();
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                Toast.makeText(getApplicationContext(), getString(R.string.gcm_ready), Toast.LENGTH_LONG)
                        .show();

            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.gcm_not_ready), Toast.LENGTH_LONG)
                        .show();

            }
        }
    };

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }

    //Evento click para iniciar sesin
    btnIniciarSesion.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startSession();
        }
    });

}

From source file:com.fastbootmobile.twofactorauthdemo.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.info_layout);

    Button regButton = (Button) findViewById(R.id.register);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.getString("otp", null) != null) {
            TextView txt = (TextView) findViewById(R.id.txt);
            regButton.setVisibility(View.GONE);
            txt.setText("One Time Password :  " + extras.getString("otp", null));
            return;
        }/*from w  w w .  j a va  2 s  .c o m*/
    }

    mReg = new OwnPushRegistrant(this);
    mHandler = new Handler();
    receiver = new RegisterReceiver(new Handler());

    IntentFilter filter = new IntentFilter(OwnPushClient.INTENT_REGISTER);
    filter.addCategory(BuildConfig.APP_PUBLIC_KEY);

    registerReceiver(receiver, filter);

    final SharedPreferences prefs = this.getApplicationContext().getSharedPreferences(OwnPushClient.PREF_PUSH,
            Context.MODE_PRIVATE);

    if (!prefs.getBoolean(OwnPushClient.PREF_REG_DONE, false)) {

        regButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OwnPushCrypto fp = new OwnPushCrypto();
                OwnPushCrypto.AppKeyPair keys = fp.generateInstallKey();

                boolean ret = mReg.register(BuildConfig.APP_PUBLIC_KEY, keys.getPublicKey());

                if (ret) {
                    //STORE THEM
                    prefs.edit().putString(OwnPushClient.PREF_PUBLIC_KEY, keys.getPublicKey()).commit();
                    prefs.edit().putString(OwnPushClient.PREF_PRIVATE_KEY, keys.getPrivateKey()).commit();
                }
            }
        });
    } else {
        regButton.setVisibility(View.GONE);

        updateUI();

        if (prefs.getString("device_uid", null) == null) {
            registerWithBackend();
        }
    }

}

From source file:de.janrenz.app.mediathek.ArdMediathekProvider.java

@Override
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
    String url = "";
    String queryparam = uri.getQueryParameter("timestamp");
    ;/*from   www.j  a  v a 2  s .c  om*/
    Integer timestamp = null;
    if (queryparam == null) {
        Date dt = new Date();
        timestamp = dt.getSeconds();
    } else {

        timestamp = Integer.parseInt(queryparam);
    }

    String queryparammethod = uri.getQueryParameter("method");
    if (queryparammethod == null) {
        queryparammethod = "list";
        url = "http://m-service.daserste.de/appservice/1.4.2/video/list/" + timestamp
                + "?func=getVideoList&unixTimestamp=" + timestamp;
    } else if (queryparammethod.equalsIgnoreCase("search")) {
        // url = /appservice/1.4.1/search/heiter/0/25?func=getSearchResultList&searchPattern=heiter&searchOffset=0&searchLength=25
        String searchQuery = uri.getQueryParameter("query");
        //!TODO make this url safe
        url = "http://m-service.daserste.de/appservice/1.4.2/search/" + URLEncoder.encode(searchQuery)
                + "/0/50?func=getSearchResultList&searchPattern=" + URLEncoder.encode(searchQuery)
                + "&searchOffset=0&searchLength=50";
    } else if (queryparammethod.equalsIgnoreCase("broadcast")) {
        url = "http://m-service.daserste.de/appservice/1.4.2/broadcast/current/" + timestamp
                + "?func=getCurrentBroadcast&unixTimestamp=" + timestamp;
    } else {
        // oh oh
    }
    String queryparamReload = uri.getQueryParameter("reload");
    String queryExtReload = "";
    if (queryparamReload != null) {
        queryExtReload = "&reload=" + Math.random();
    }

    String result = "";
    result = readJSONFeed(url);
    MatrixCursor cursor = new MatrixCursor(new String[] { "_id", "title", "subtitle", "image", "extId",
            "startTime", "startTimeAsTimestamp", "isLive" });
    if (result == "") {
        return cursor;
    }

    if (queryparammethod.equalsIgnoreCase("broadcast")) {
        cursor = (MatrixCursor) processResultForBroadcast(result);
    } else if (queryparammethod.equalsIgnoreCase("search")) {
        cursor = (MatrixCursor) processResultForList(result, true);
    } else {
        Boolean orderParam = false;
        try {
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
            Boolean reverse = sharedPref.getBoolean(SettingsActivity.REVERSE_LIST_ORDER, false);

            //reverse is menat by user perspective here, by default its false
            if (reverse == true) {
                orderParam = true;
            }
        } catch (Exception e) {
            // use the default if we cant fetch it
        }
        //Log.e("order Param", orderParam.toString());
        cursor = (MatrixCursor) processResultForList(result, orderParam);
    }

    return (Cursor) cursor;
}

From source file:com.notifry.android.ChooseAccount.java

@Override
public void onResume() {
    super.onResume();

    // When coming back, refresh our list of accounts.
    refreshView();//w w  w . ja v  a  2  s . co m

    // Show the help.
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    if (settings.getBoolean("chooseAccountFirstTime", true)) {
        // Show first time help.
        new AlertDialog.Builder(this).setTitle(getString(R.string.accounts_and_sources))
                .setMessage(getString(R.string.accounts_help)).setPositiveButton(getString(R.string.ok), null)
                .show();

        // And don't show again.
        Editor editor = settings.edit();
        editor.putBoolean("chooseAccountFirstTime", false);
        editor.commit();
    }
}

From source file:com.nextgis.mobile.DataSendService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(MainActivity.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)) {
        //Toast.makeText(getApplicationContext(), "Send position service stoped", Toast.LENGTH_SHORT).show();
        stopSelf();/*from   www.  jav  a 2 s  .  c  o m*/
    } else if (action.equals(ACTION_START)) {
        SharedPreferences prefs = getSharedPreferences(PreferencesActivity.SERVICE_PREF,
                MODE_PRIVATE | MODE_MULTI_PROCESS);
        boolean bStart = prefs.getBoolean(PreferencesActivity.KEY_PREF_SW_SENDPOS_SRV, false);
        if (bStart)
            new SendPositionDataTask().execute(getApplicationContext());
        else
            //Toast.makeText(getApplicationContext(), "Send position service started", Toast.LENGTH_SHORT).show();
            stopSelf();
    }
    return START_STICKY;
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsActivity.java

/** Handles item selections */
@Override//from  w  w w .j a  v a  2 s  .  com
public boolean onOptionsItemSelected(MenuItem item) {
    Resources res = this.getResources();
    switch (item.getItemId()) {
    case android.R.id.home:
        closeStudyOptions();
        return true;

    case MENU_PREFERENCES:
        startActivityForResult(new Intent(this, Preferences.class), StudyOptionsFragment.PREFERENCES_UPDATE);
        if (AnkiDroidApp.SDK_VERSION > 4) {
            ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.FADE);
        }
        return true;

    case MENU_ROTATE:
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        return true;

    case MENU_NIGHT:
        SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
        if (preferences.getBoolean("invertedColors", false)) {
            preferences.edit().putBoolean("invertedColors", false).commit();
            item.setIcon(R.drawable.ic_menu_night);
        } else {
            preferences.edit().putBoolean("invertedColors", true).commit();
            item.setIcon(R.drawable.ic_menu_night_checked);
        }
        return true;
    case DeckPicker.MENU_CREATE_DYNAMIC_DECK:
        StyledDialog.Builder builder = new StyledDialog.Builder(StudyOptionsActivity.this);
        builder.setTitle(res.getString(R.string.new_deck));

        mDialogEditText = new EditText(StudyOptionsActivity.this);
        ArrayList<String> names = AnkiDroidApp.getCol().getDecks().allNames();
        int n = 1;
        String cramDeckName = "Cram 1";
        while (names.contains(cramDeckName)) {
            n++;
            cramDeckName = "Cram " + n;
        }
        mDialogEditText.setText(cramDeckName);
        // mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
        builder.setView(mDialogEditText, false, false);
        builder.setPositiveButton(res.getString(R.string.create), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                long id;
                Bundle initialConfig = new Bundle();
                try {
                    initialConfig.putString("searchSuffix",
                            "'deck:" + AnkiDroidApp.getCol().getDecks().current().getString("name") + "'");
                    id = AnkiDroidApp.getCol().getDecks().newDyn(mDialogEditText.getText().toString());
                    AnkiDroidApp.getCol().getDecks().get(id);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                loadContent(false, initialConfig);
            }
        });
        builder.setNegativeButton(res.getString(R.string.cancel), null);
        builder.create().show();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:de.janrenz.app.mediathek.ArdMediathekProvider.java

private Cursor processResultForList(String result, Boolean doReverse) {
    MatrixCursor cursor = new MatrixCursor(new String[] { "_id", "title", "subtitle", "image", "extId",
            "startTime", "startTimeAsTimestamp", "isLive" });
    try {/*w  w w  . ja  va 2s. c  o  m*/
        JSONArray jsonArray = new JSONArray(result);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json_data;
            if (doReverse == true) {
                json_data = jsonArray.getJSONObject(jsonArray.length() - (i + 1));
            } else {
                json_data = jsonArray.getJSONObject(i);
            }

            // build the Headline
            String t2 = android.text.Html.fromHtml(json_data.getString("Title3")).toString();
            String t3 = android.text.Html.fromHtml(json_data.getString("Title2")).toString();

            // Handle grouped views
            Boolean IsGrouped = false;
            try {
                IsGrouped = json_data.getBoolean("IsGrouped");
            } catch (Exception e) {
                //this value might not exists
            }
            if (IsGrouped) {
                String mtime = json_data.getString("BTime").toString();
                String cliplisturl = "http://m-service.daserste.de/appservice/1.4.2/video/clip/list/" + mtime
                        + "/" + URLEncoder.encode(t3) + "?func=getVideoClipList&clipTimestamp=" + mtime
                        + "&clipTitle=" + URLEncoder.encode(t3);
                String result2 = "";
                result2 = readJSONFeed(cliplisturl);
                JSONArray jsonArray2 = new JSONArray(result2);

                for (int j = 0; j < jsonArray2.length(); j++) {
                    JSONObject json_data2 = jsonArray2.getJSONObject(j);
                    t2 = android.text.Html.fromHtml(json_data2.getString("Title3")).toString();
                    t3 = android.text.Html.fromHtml(json_data2.getString("Title2")).toString();

                    // only add movie if it has a video
                    if (android.text.Html.fromHtml(json_data2.getString("VId")).toString() != "") {

                        cursor.addRow(new Object[] { 1000 + j, t2, t3,
                                json_data2.getString("ImageUrl").toString(), json_data2.getString("VId"),
                                json_data2.getString("BTimeF").toString(),
                                json_data2.getString("BTime").toString(), json_data2.getString("IsLive") });
                    }

                }
            }
            Boolean hideLive = false;
            try {
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
                hideLive = sharedPref.getBoolean(SettingsActivity.HIDE_LIVE, false);
            } catch (Exception e) {
            }

            Boolean IsGrouped2 = false;
            try {
                IsGrouped2 = json_data.getBoolean("IsGrouped");
            } catch (Exception e) {
                //this value might not exists
            }
            if (!IsGrouped2) {
                if (!json_data.getString("VId").equalsIgnoreCase("")) {
                    if (json_data.getString("IsLive").toString().equalsIgnoreCase("false")
                            || (json_data.getString("IsLive").toString().equalsIgnoreCase("true")
                                    && hideLive == false))
                        cursor.addRow(new Object[] { i, t2, t3, json_data.getString("ImageUrl").toString(),
                                json_data.getString("VId"), json_data.getString("BTimeF").toString(),
                                json_data.getString("BTime").toString(), json_data.getString("IsLive") });
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return (Cursor) cursor;
    }
    return (Cursor) cursor;
}

From source file:de.ub0r.android.websms.connector.innosend.ConnectorInnosend.java

/**
 * {@inheritDoc}//w w w.j  av  a 2 s.  co m
 */
@Override
public final ConnectorSpec initSpec(final Context context) {
    final String name = context.getString(R.string.connector_innosend_name);
    ConnectorSpec c = new ConnectorSpec(name);
    c.setAuthor(context.getString(R.string.connector_innosend_author));
    c.setBalance(null);
    c.setCapabilities(ConnectorSpec.CAPABILITIES_UPDATE | ConnectorSpec.CAPABILITIES_SEND
            | ConnectorSpec.CAPABILITIES_PREFS);
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    if (!p.getBoolean(PREFS_HIDE_FREE, false)) {
        c.addSubConnector(ID_FREE, context.getString(R.string.free), SubConnectorSpec.FEATURE_NONE);
    }
    if (!p.getBoolean(PREFS_HIDE_TYPE3, false)) {
        c.addSubConnector(ID_TYPE3, context.getString(R.string.type3), SubConnectorSpec.FEATURE_NONE);
    }
    if (!p.getBoolean(PREFS_HIDE_WO_SENDER, false)) {
        c.addSubConnector(ID_WO_SENDER, context.getString(R.string.wo_sender),
                SubConnectorSpec.FEATURE_SENDLATER | SubConnectorSpec.FEATURE_FLASHSMS);
    }
    if (!p.getBoolean(PREFS_HIDE_W_SENDER, false)) {
        c.addSubConnector(ID_W_SENDER, context.getString(R.string.w_sender),
                SubConnectorSpec.FEATURE_CUSTOMSENDER | SubConnectorSpec.FEATURE_SENDLATER);
    }
    return c;
}