List of usage examples for android.content SharedPreferences getLong
long getLong(String key, long defValue);
From source file:org.tigase.messenger.phone.pro.service.XMPPService.java
private void connectJaxmpp(final Jaxmpp jaxmpp, final Date date) { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); long presenceId = sharedPref.getLong("presence", CPresence.OFFLINE); if (presenceId == CPresence.OFFLINE) return;//from w w w . j a va 2s . c om if (isLocked(jaxmpp.getSessionObject())) { Log.v(TAG, "cancelling connect for " + jaxmpp.getSessionObject().getUserBareJid() + " because it is locked"); return; } final Runnable r = new Runnable() { @Override public void run() { Log.v(TAG, "Trying to connect account " + jaxmpp.getSessionObject().getUserBareJid()); lock(jaxmpp.getSessionObject(), false); if (isDisabled(jaxmpp.getSessionObject())) { Log.v(TAG, "cancelling connect for " + jaxmpp.getSessionObject().getUserBareJid() + " because it is disabled"); return; } setUsedNetworkType(getActiveNetworkType()); int tmpNetworkType = getUsedNetworkType(); Log.v(TAG, "Network state is " + tmpNetworkType); if (tmpNetworkType != -1) { (new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { if (jaxmpp.isConnected()) { Log.v(TAG, "cancelling connect for " + jaxmpp.getSessionObject().getUserBareJid() + " because it is connected already"); return null; } final Connector.State state = jaxmpp.getSessionObject() .getProperty(Connector.CONNECTOR_STAGE_KEY); Log.v(TAG, "Account " + jaxmpp.getSessionObject().getUserBareJid() + " is in state " + state); if (state != null && state != Connector.State.disconnected) { Log.v(TAG, "cancelling connect for " + jaxmpp.getSessionObject().getUserBareJid() + " because it state " + state); return null; } jaxmpp.getSessionObject().setProperty("messenger#error", null); jaxmpp.login(); } catch (Exception e) { if (e.getCause() instanceof SecureTrustManagerFactory.DataCertificateException) { jaxmpp.getSessionObject().setProperty("CC:DISABLED", Boolean.TRUE); processCertificateError(jaxmpp, (SecureTrustManagerFactory.DataCertificateException) e.getCause()); } else { Log.e(TAG, "Can't connect account " + jaxmpp.getSessionObject().getUserBareJid(), e); } } return null; } }).execute(); } } }; lock(jaxmpp.getSessionObject(), true); if (date == null) { Log.d(TAG, "Starting connection NOW"); r.run(); } else { Log.d(TAG, "Starting connection LATER"); timer.schedule(new TimerTask() { @Override public void run() { r.run(); } }, date); } }
From source file:pandroid.agent.PandroidAgentListener.java
private String getSharedData(String preferenceName, String tokenName, String defaultValue, String type) { SharedPreferences agentPreferences = getApplicationContext().getSharedPreferences( getApplicationContext().getString(R.string.const_string_preferences), Activity.MODE_PRIVATE); if (type == "boolean") { boolean a = agentPreferences.getBoolean(tokenName, Boolean.parseBoolean(defaultValue)); return Boolean.valueOf(a).toString(); } else if (type == "float") { float a = agentPreferences.getFloat(tokenName, Float.parseFloat(defaultValue)); return Float.valueOf(a).toString(); } else if (type == "integer") { int a = agentPreferences.getInt(tokenName, Integer.parseInt(defaultValue)); return Integer.valueOf(a).toString(); } else if (type == "long") { long a = agentPreferences.getLong(tokenName, Long.parseLong(defaultValue)); return Long.valueOf(a).toString(); } else if (type == "string") { return agentPreferences.getString(tokenName, defaultValue); }/*from w w w. j a va 2 s .c o m*/ return ""; }
From source file:com.Beat.RingdroidEditActivity.java
/** * Nothing nefarious about this; the purpose is just to * uniquely identify each user so we don't double-count the same * ringtone - without actually identifying the actual user. *///from ww w . j a va 2s .c om long getUniqueId() { SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); long uniqueId = prefs.getLong(PREF_UNIQUE_ID, 0); if (uniqueId == 0) { uniqueId = new Random().nextLong(); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putLong(PREF_UNIQUE_ID, uniqueId); prefsEditor.commit(); } return uniqueId; }
From source file:ru.valle.btc.MainActivity.java
private void tryToGenerateSpendingTransaction() { final ArrayList<UnspentOutputInfo> unspentOutputs = verifiedUnspentOutputsForTx; final String outputAddress = verifiedRecipientAddressForTx; final long requestedAmountToSend = verifiedAmountToSendForTx; final KeyPair keyPair = verifiedKeyPairForTx; final boolean inputsComesFromJson = verifiedUnspentOutputsComesFromJson; final int predefinedConfirmationsCount = verifiedConfirmationsCount; spendTxDescriptionView.setVisibility(View.GONE); spendTxWarningView.setVisibility(View.GONE); spendTxEdit.setText(""); spendTxEdit.setVisibility(View.GONE); sendTxInBrowserButton.setVisibility(View.GONE); findViewById(R.id.spend_tx_required_age_for_free_tx).setVisibility(View.GONE); // https://blockchain.info/pushtx if (unspentOutputs != null && !unspentOutputs.isEmpty() && !TextUtils.isEmpty(outputAddress) && keyPair != null && requestedAmountToSend >= SEND_MAX && requestedAmountToSend != 0 && !TextUtils.isEmpty(keyPair.address)) { cancelAllRunningTasks();//www . j a v a 2 s . co m generateTransactionTask = new AsyncTask<Void, Void, GenerateTransactionResult>() { @Override protected GenerateTransactionResult doInBackground(Void... voids) { final Transaction spendTx; try { long availableAmount = 0; for (UnspentOutputInfo unspentOutputInfo : unspentOutputs) { availableAmount += unspentOutputInfo.value; } long amount; if (availableAmount == requestedAmountToSend || requestedAmountToSend == SEND_MAX) { //transfer maximum possible amount amount = -1; } else { amount = requestedAmountToSend; } long extraFee; SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(MainActivity.this); try { extraFee = preferences.getLong(PreferencesActivity.PREF_EXTRA_FEE, FeePreference.PREF_EXTRA_FEE_DEFAULT); } catch (ClassCastException e) { preferences.edit().remove(PreferencesActivity.PREF_EXTRA_FEE) .putLong(PreferencesActivity.PREF_EXTRA_FEE, FeePreference.PREF_EXTRA_FEE_DEFAULT) .commit(); extraFee = FeePreference.PREF_EXTRA_FEE_DEFAULT; } spendTx = BTCUtils.createTransaction(unspentOutputs, outputAddress, keyPair.address, amount, extraFee, keyPair.publicKey, keyPair.privateKey); //6. double check that generated transaction is valid Transaction.Script[] relatedScripts = new Transaction.Script[spendTx.inputs.length]; for (int i = 0; i < spendTx.inputs.length; i++) { Transaction.Input input = spendTx.inputs[i]; for (UnspentOutputInfo unspentOutput : unspentOutputs) { if (Arrays.equals(unspentOutput.txHash, input.outPoint.hash) && unspentOutput.outputIndex == input.outPoint.index) { relatedScripts[i] = unspentOutput.script; break; } } } BTCUtils.verify(relatedScripts, spendTx); } catch (BitcoinException e) { switch (e.errorCode) { case BitcoinException.ERR_INSUFFICIENT_FUNDS: return new GenerateTransactionResult(getString(R.string.error_not_enough_funds), GenerateTransactionResult.ERROR_SOURCE_AMOUNT_FIELD); case BitcoinException.ERR_FEE_IS_TOO_BIG: return new GenerateTransactionResult(getString(R.string.generated_tx_have_too_big_fee), GenerateTransactionResult.ERROR_SOURCE_INPUT_TX_FIELD); case BitcoinException.ERR_MEANINGLESS_OPERATION://input, output and change addresses are same. return new GenerateTransactionResult(getString(R.string.output_address_same_as_input), GenerateTransactionResult.ERROR_SOURCE_ADDRESS_FIELD); // case BitcoinException.ERR_INCORRECT_PASSWORD // case BitcoinException.ERR_WRONG_TYPE: // case BitcoinException.ERR_FEE_IS_LESS_THEN_ZERO // case BitcoinException.ERR_CHANGE_IS_LESS_THEN_ZERO // case BitcoinException.ERR_AMOUNT_TO_SEND_IS_LESS_THEN_ZERO default: return new GenerateTransactionResult( getString(R.string.error_failed_to_create_transaction) + ": " + e.getMessage(), GenerateTransactionResult.ERROR_SOURCE_UNKNOWN); } } catch (Exception e) { return new GenerateTransactionResult( getString(R.string.error_failed_to_create_transaction) + ": " + e, GenerateTransactionResult.ERROR_SOURCE_UNKNOWN); } long inValue = 0; for (Transaction.Input input : spendTx.inputs) { for (UnspentOutputInfo unspentOutput : unspentOutputs) { if (Arrays.equals(unspentOutput.txHash, input.outPoint.hash) && unspentOutput.outputIndex == input.outPoint.index) { inValue += unspentOutput.value; } } } long outValue = 0; for (Transaction.Output output : spendTx.outputs) { outValue += output.value; } long fee = inValue - outValue; return new GenerateTransactionResult(spendTx, fee); } @Override protected void onPostExecute(GenerateTransactionResult result) { super.onPostExecute(result); generateTransactionTask = null; if (result != null) { final TextView rawTxToSpendErr = (TextView) findViewById(R.id.err_raw_tx); if (result.tx != null) { String amountStr = null; Transaction.Script out = null; try { out = Transaction.Script.buildOutput(outputAddress); } catch (BitcoinException ignore) { } if (result.tx.outputs[0].script.equals(out)) { amountStr = BTCUtils.formatValue(result.tx.outputs[0].value); } if (amountStr == null) { rawTxToSpendErr.setText(R.string.error_unknown); } else { String descStr; String feeStr = BTCUtils.formatValue(result.fee); String changeStr; if (result.tx.outputs.length == 1) { changeStr = null; descStr = getString(R.string.spend_tx_description, amountStr, keyPair.address, outputAddress, feeStr); } else if (result.tx.outputs.length == 2) { changeStr = BTCUtils.formatValue(result.tx.outputs[1].value); descStr = getString(R.string.spend_tx_with_change_description, amountStr, keyPair.address, outputAddress, feeStr, changeStr); } else { throw new RuntimeException(); } SpannableStringBuilder descBuilder = new SpannableStringBuilder(descStr); int spanBegin = descStr.indexOf(keyPair.address); if (spanBegin >= 0) {//from ForegroundColorSpan addressColorSpan = new ForegroundColorSpan( getColor(MainActivity.this, R.color.dark_orange)); descBuilder.setSpan(addressColorSpan, spanBegin, spanBegin + keyPair.address.length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } if (spanBegin >= 0) { spanBegin = descStr.indexOf(keyPair.address, spanBegin + 1); if (spanBegin >= 0) {//change ForegroundColorSpan addressColorSpan = new ForegroundColorSpan( getColor(MainActivity.this, R.color.dark_orange)); descBuilder.setSpan(addressColorSpan, spanBegin, spanBegin + keyPair.address.length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } } spanBegin = descStr.indexOf(outputAddress); if (spanBegin >= 0) {//dest ForegroundColorSpan addressColorSpan = new ForegroundColorSpan( getColor(MainActivity.this, R.color.dark_green)); descBuilder.setSpan(addressColorSpan, spanBegin, spanBegin + outputAddress.length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } final String nbspBtc = "\u00a0BTC"; spanBegin = descStr.indexOf(amountStr + nbspBtc); if (spanBegin >= 0) { descBuilder.setSpan(new StyleSpan(Typeface.BOLD), spanBegin, spanBegin + amountStr.length() + nbspBtc.length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } spanBegin = descStr.indexOf(feeStr + nbspBtc, spanBegin); if (spanBegin >= 0) { descBuilder.setSpan(new StyleSpan(Typeface.BOLD), spanBegin, spanBegin + feeStr.length() + nbspBtc.length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } if (changeStr != null) { spanBegin = descStr.indexOf(changeStr + nbspBtc, spanBegin); if (spanBegin >= 0) { descBuilder.setSpan(new StyleSpan(Typeface.BOLD), spanBegin, spanBegin + changeStr.length() + nbspBtc.length(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } } spendTxDescriptionView.setText(descBuilder); spendTxDescriptionView.setVisibility(View.VISIBLE); spendTxWarningView.setVisibility(View.VISIBLE); spendTxEdit.setText(BTCUtils.toHex(result.tx.getBytes())); spendTxEdit.setVisibility(View.VISIBLE); sendTxInBrowserButton.setVisibility(View.VISIBLE); TextView maxAgeView = (TextView) findViewById( R.id.spend_tx_required_age_for_free_tx); CheckBox maxAgeCheckBox = (CheckBox) findViewById( R.id.spend_tx_required_age_for_free_tx_checkbox); if (!inputsComesFromJson) { if (!showNotEligibleForNoFeeBecauseOfBasicConstrains(maxAgeView, result.tx)) { final int confirmations = (int) (BTCUtils.MIN_PRIORITY_FOR_NO_FEE * result.tx.getBytes().length / unspentOutputs.get(0).value); float daysFloat = confirmations / BTCUtils.EXPECTED_BLOCKS_PER_DAY; String timePeriodStr; if (daysFloat <= 1) { int hours = (int) Math.round(Math.ceil(daysFloat / 24)); timePeriodStr = getResources().getQuantityString(R.plurals.hours, hours, hours); } else { int days = (int) Math.round(Math.ceil(daysFloat)); timePeriodStr = getResources().getQuantityString(R.plurals.days, days, days); } maxAgeCheckBox.setText(getString(R.string.input_tx_is_old_enough, getResources().getQuantityString(R.plurals.confirmations, confirmations, confirmations), timePeriodStr)); maxAgeCheckBox.setVisibility(View.VISIBLE); maxAgeCheckBox.setOnCheckedChangeListener(null); maxAgeCheckBox.setChecked(predefinedConfirmationsCount > 0); maxAgeCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { verifiedConfirmationsCount = isChecked ? confirmations : -1; onUnspentOutputsInfoChanged(); } }); } else { maxAgeCheckBox.setVisibility(View.GONE); } } else { showNotEligibleForNoFeeBecauseOfBasicConstrains(maxAgeView, result.tx); } } } else if (result.errorSource == GenerateTransactionResult.ERROR_SOURCE_INPUT_TX_FIELD) { rawTxToSpendErr.setText(result.errorMessage); } else if (result.errorSource == GenerateTransactionResult.ERROR_SOURCE_ADDRESS_FIELD || result.errorSource == GenerateTransactionResult.HINT_FOR_ADDRESS_FIELD) { ((TextView) findViewById(R.id.err_recipient_address)).setText(result.errorMessage); } else if (!TextUtils.isEmpty(result.errorMessage) && result.errorSource == GenerateTransactionResult.ERROR_SOURCE_UNKNOWN) { new AlertDialog.Builder(MainActivity.this).setMessage(result.errorMessage) .setPositiveButton(android.R.string.ok, null).show(); } ((TextView) findViewById(R.id.err_amount)) .setText(result.errorSource == GenerateTransactionResult.ERROR_SOURCE_AMOUNT_FIELD ? result.errorMessage : ""); } } private boolean showNotEligibleForNoFeeBecauseOfBasicConstrains(TextView maxAgeView, Transaction tx) { long minOutput = Long.MAX_VALUE; for (Transaction.Output output : tx.outputs) { minOutput = Math.min(output.value, minOutput); } int txLen = tx.getBytes().length; if (txLen >= BTCUtils.MAX_TX_LEN_FOR_NO_FEE) { maxAgeView.setText( getResources().getQuantityText(R.plurals.tx_size_too_big_to_be_free, txLen)); maxAgeView.setVisibility(View.VISIBLE); return true; } else if (minOutput < BTCUtils.MIN_MIN_OUTPUT_VALUE_FOR_NO_FEE) { maxAgeView .setText(getString(R.string.tx_output_is_too_small, BTCUtils.formatValue(minOutput), BTCUtils.formatValue(BTCUtils.MIN_MIN_OUTPUT_VALUE_FOR_NO_FEE))); maxAgeView.setVisibility(View.VISIBLE); return true; } maxAgeView.setVisibility(View.GONE); return false; } }.execute(); } }
From source file:website.openeng.anki.DeckPicker.java
private void automaticSync() { SharedPreferences preferences = KanjiDroidApp.getSharedPrefs(getBaseContext()); // Check whether the option is selected, the user is signed in and last sync was AUTOMATIC_SYNC_TIME ago // (currently 10 minutes) String hkey = preferences.getString("hkey", ""); long lastSyncTime = preferences.getLong("lastSyncTime", 0); if (hkey.length() != 0 && preferences.getBoolean("automaticSyncMode", false) && Utils.intNow(1000) - lastSyncTime > AUTOMATIC_SYNC_MIN_INTERVAL) { sync();//w w w . j a va2 s . c om } }
From source file:com.panahit.ui.Components.EmojiView.java
public void loadRecents() { SharedPreferences preferences = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE); lastGifLoadTime = preferences.getLong("lastGifLoadTime", 0); String str;/*w ww . ja v a 2s.c om*/ try { emojiUseHistory.clear(); if (preferences.contains("emojis")) { str = preferences.getString("emojis", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); for (String arg : args) { String[] args2 = arg.split("="); long value = Long.parseLong(args2[0]); String string = ""; for (int a = 0; a < 4; a++) { char ch = (char) value; string = String.valueOf(ch) + string; value >>= 16; if (value == 0) { break; } } if (string.length() > 0) { emojiUseHistory.put(string, Integer.parseInt(args2[1])); } } } preferences.edit().remove("emojis").commit(); saveRecentEmoji(); } else { str = preferences.getString("emojis2", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); for (String arg : args) { String[] args2 = arg.split("="); emojiUseHistory.put(args2[0], Integer.parseInt(args2[1])); } } } if (emojiUseHistory.isEmpty()) { String[] newRecent = new String[] { "\uD83D\uDE02", "\uD83D\uDE18", "\u2764", "\uD83D\uDE0D", "\uD83D\uDE0A", "\uD83D\uDE01", "\uD83D\uDC4D", "\u263A", "\uD83D\uDE14", "\uD83D\uDE04", "\uD83D\uDE2D", "\uD83D\uDC8B", "\uD83D\uDE12", "\uD83D\uDE33", "\uD83D\uDE1C", "\uD83D\uDE48", "\uD83D\uDE09", "\uD83D\uDE03", "\uD83D\uDE22", "\uD83D\uDE1D", "\uD83D\uDE31", "\uD83D\uDE21", "\uD83D\uDE0F", "\uD83D\uDE1E", "\uD83D\uDE05", "\uD83D\uDE1A", "\uD83D\uDE4A", "\uD83D\uDE0C", "\uD83D\uDE00", "\uD83D\uDE0B", "\uD83D\uDE06", "\uD83D\uDC4C", "\uD83D\uDE10", "\uD83D\uDE15" }; for (int i = 0; i < newRecent.length; i++) { emojiUseHistory.put(newRecent[i], newRecent.length - i); } saveRecentEmoji(); } sortEmoji(); adapters.get(0).notifyDataSetChanged(); } catch (Exception e) { FileLog.e("tmessages", e); } try { str = preferences.getString("color", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); for (int a = 0; a < args.length; a++) { String arg = args[a]; String[] args2 = arg.split("="); emojiColor.put(args2[0], args2[1]); } } } catch (Exception e) { FileLog.e("tmessages", e); } if (showStickers) { try { newRecentStickers.clear(); str = preferences.getString("stickers", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); final HashMap<Long, Integer> stickersUseHistory = new HashMap<>(); for (int a = 0; a < args.length; a++) { String arg = args[a]; String[] args2 = arg.split("="); Long key = Long.parseLong(args2[0]); stickersUseHistory.put(key, Integer.parseInt(args2[1])); newRecentStickers.add(key); } Collections.sort(newRecentStickers, new Comparator<Long>() { @Override public int compare(Long lhs, Long rhs) { Integer count1 = stickersUseHistory.get(lhs); Integer count2 = stickersUseHistory.get(rhs); if (count1 == null) { count1 = 0; } if (count2 == null) { count2 = 0; } if (count1 > count2) { return -1; } else if (count1 < count2) { return 1; } return 0; } }); preferences.edit().remove("stickers").commit(); saveRecentStickers(); } else { str = preferences.getString("stickers2", ""); String[] args = str.split(","); for (int a = 0; a < args.length; a++) { newRecentStickers.add(Long.parseLong(args[a])); } } sortStickers(); updateStickerTabs(); } catch (Exception e) { FileLog.e("tmessages", e); } } }
From source file:com.getpillion.gcm.GcmIntentService.java
@Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras();//from ww w. j av a2s . c o m GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { //sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { //sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. /*for (int i = 0; i < 5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());*/ Log.d("GcmIntentService", "Got data from upstream " + extras.toString()); if (Konotor.getInstance(getApplicationContext()).isKonotorMessage(intent)) { Log.d("Konotor", "Got konotor message"); Konotor.getInstance(getApplicationContext()).handleGcmOnMessage(intent); return; } String simpleClassName = extras.getString("model_name"); String json = extras.getString("json"); Log.d("GcmIntentService", "json received for update - " + json + " for " + simpleClassName); Gson gson = new Gson(); Intent targetIntent = null; String msg = null; SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constant.PREFS_NAME, 0); if (simpleClassName.equals("Ride")) { //check if ride timing or vehicle info got updated try { Ride updatedRide = gson.fromJson(json, Ride.class); Ride ride = Ride.find(Ride.class, "global_id = ?", String.valueOf(updatedRide.globalId)) .get(0); Ride.updateFromUpstream(updatedRide); targetIntent = new Intent(this, RideInfoActivity.class); targetIntent.putExtra("rideId", ride.getId()); msg = "Ride creator has updated the ride"; } catch (Exception e) { e.printStackTrace(); } } if (simpleClassName.equals("User")) { User.updateFromUpstream(gson.fromJson(json, User.class)); //lets not send notification for user info update } if (simpleClassName.equals("RideUserMapping")) { //this is important RideUserMapping rideUserMapping = gson.fromJson(json, RideUserMapping.class); //we need the ride Ride ride = Ride.find(Ride.class, "global_id = ?", String.valueOf(rideUserMapping.rideId)) .get(0); targetIntent = new Intent(this, RideInfoActivity.class); targetIntent.putExtra("rideId", ride.getId()); RideUserMapping myEntry = RideUserMapping .find(RideUserMapping.class, "ride_id = ? AND user_id = ?", String.valueOf(ride.getId()), String.valueOf(sharedPref.getLong("userId", 0L))) .get(0); RideUserMapping updated = RideUserMapping.updateFromUpstream(ride, rideUserMapping); //broadcast only for ride requester. The flow will not go into the subsequent if because of the user's status if (updated.userId == sharedPref.getLong("userId", 0L)) { switch (updated.status) { case Constant.ACCEPTED: //show to requester msg = "Your ride request is approved"; break; case Constant.REJECTED: //show to the requester - request rejected msg = "Sorry, your request has been rejected"; break; } } //broadcast for everyone if (myEntry.status != Constant.REQUESTED && myEntry.status != Constant.REJECTED && myEntry.status != Constant.CANCELLED) { switch (updated.status) { case Constant.REQUESTED: //show only to owner if (myEntry.isOwner) msg = "New ride request"; break; case Constant.CANCELLED: if (updated.isOwner) { msg = "Owner has cancelled the ride"; //for other active users } else { msg = "One traveller backed out"; //for owner } break; case Constant.CHECKED_IN: //show to all - {traveller} has reached his start point msg = "One traveller has reached his pickup point"; break; case Constant.STARTED: //show to all - ride has been started msg = "Ride has started."; break; } } } if (simpleClassName.equals("WorkHistory")) { //lets just leave this } Log.d("GcmIntentService", "message to the user - " + msg); if (msg != null) sendNotification(targetIntent, msg); Log.i(TAG, "Received: " + extras.toString()); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); }
From source file:com.nextgis.mobile.fragment.MapFragment.java
@Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (null == savedInstanceState) { mMode = MODE_NORMAL;//from ww w. j a v a 2 s .co m } else { mMode = savedInstanceState.getInt(KEY_MODE); int layerId = savedInstanceState.getInt(BUNDLE_KEY_LAYER); ILayer layer = mMap.getLayerById(layerId); Feature feature = null; if (null != layer && layer instanceof VectorLayer) { mSelectedLayer = (VectorLayer) layer; if (savedInstanceState.containsKey(BUNDLE_KEY_SAVED_FEATURE)) { GeoGeometry geometry = null; try { geometry = GeoGeometryFactory .fromBlob(savedInstanceState.getByteArray(BUNDLE_KEY_SAVED_FEATURE)); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } feature = new Feature(); feature.setId(savedInstanceState.getLong(BUNDLE_KEY_FEATURE_ID)); feature.setGeometry(geometry); } } mEditLayerOverlay.setSelectedLayer(mSelectedLayer); mEditLayerOverlay.setSelectedFeature(feature); } if (WalkEditService.isServiceRunning(getContext())) { SharedPreferences preferences = getContext().getSharedPreferences(WalkEditService.TEMP_PREFERENCES, Constants.MODE_MULTI_PROCESS); int layerId = preferences.getInt(ConstantsUI.KEY_LAYER_ID, NOT_FOUND); long featureId = preferences.getLong(ConstantsUI.KEY_FEATURE_ID, NOT_FOUND); ILayer layer = mMap.getMap().getLayerById(layerId); if (layer != null && layer instanceof VectorLayer) { mSelectedLayer = (VectorLayer) layer; mEditLayerOverlay.setSelectedLayer(mSelectedLayer); if (featureId > NOT_FOUND) mEditLayerOverlay.setSelectedFeature(featureId); else mEditLayerOverlay.newGeometryByWalk(); GeoGeometry geometry = GeoGeometryFactory.fromWKT( preferences.getString(ConstantsUI.KEY_GEOMETRY, ""), GeoConstants.CRS_WEB_MERCATOR); if (geometry != null) mEditLayerOverlay.setGeometryFromWalkEdit(geometry); mMode = MODE_EDIT_BY_WALK; } } setMode(mMode); if (savedInstanceState != null && savedInstanceState.getBoolean(BUNDLE_KEY_IS_MEASURING, false)) startMeasuring(); }
From source file:ir.besteveryeverapp.ui.Components.EmojiView.java
public void loadRecents() { SharedPreferences preferences = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE); lastGifLoadTime = preferences.getLong("lastGifLoadTime", 0); String str;/*from ww w .j a va 2 s . co m*/ try { emojiUseHistory.clear(); if (preferences.contains("emojis")) { str = preferences.getString("emojis", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); for (String arg : args) { String[] args2 = arg.split("="); long value = Utilities.parseLong(args2[0]); String string = ""; for (int a = 0; a < 4; a++) { char ch = (char) value; string = String.valueOf(ch) + string; value >>= 16; if (value == 0) { break; } } if (string.length() > 0) { emojiUseHistory.put(string, Utilities.parseInt(args2[1])); } } } preferences.edit().remove("emojis").commit(); saveRecentEmoji(); } else { str = preferences.getString("emojis2", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); for (String arg : args) { String[] args2 = arg.split("="); emojiUseHistory.put(args2[0], Utilities.parseInt(args2[1])); } } } if (emojiUseHistory.isEmpty()) { if (!preferences.getBoolean("filled_default", false)) { String[] newRecent = new String[] { "\uD83D\uDE02", "\uD83D\uDE18", "\u2764", "\uD83D\uDE0D", "\uD83D\uDE0A", "\uD83D\uDE01", "\uD83D\uDC4D", "\u263A", "\uD83D\uDE14", "\uD83D\uDE04", "\uD83D\uDE2D", "\uD83D\uDC8B", "\uD83D\uDE12", "\uD83D\uDE33", "\uD83D\uDE1C", "\uD83D\uDE48", "\uD83D\uDE09", "\uD83D\uDE03", "\uD83D\uDE22", "\uD83D\uDE1D", "\uD83D\uDE31", "\uD83D\uDE21", "\uD83D\uDE0F", "\uD83D\uDE1E", "\uD83D\uDE05", "\uD83D\uDE1A", "\uD83D\uDE4A", "\uD83D\uDE0C", "\uD83D\uDE00", "\uD83D\uDE0B", "\uD83D\uDE06", "\uD83D\uDC4C", "\uD83D\uDE10", "\uD83D\uDE15" }; for (int i = 0; i < newRecent.length; i++) { emojiUseHistory.put(newRecent[i], newRecent.length - i); } preferences.edit().putBoolean("filled_default", true).commit(); saveRecentEmoji(); } } sortEmoji(); adapters.get(0).notifyDataSetChanged(); } catch (Exception e) { FileLog.e("tmessages", e); } try { str = preferences.getString("color", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); for (int a = 0; a < args.length; a++) { String arg = args[a]; String[] args2 = arg.split("="); emojiColor.put(args2[0], args2[1]); } } } catch (Exception e) { FileLog.e("tmessages", e); } if (showStickers) { try { newRecentStickers.clear(); str = preferences.getString("stickers", ""); if (str != null && str.length() > 0) { String[] args = str.split(","); final HashMap<Long, Integer> stickersUseHistory = new HashMap<>(); for (int a = 0; a < args.length; a++) { String arg = args[a]; String[] args2 = arg.split("="); Long key = Utilities.parseLong(args2[0]); stickersUseHistory.put(key, Utilities.parseInt(args2[1])); newRecentStickers.add(key); } Collections.sort(newRecentStickers, new Comparator<Long>() { @Override public int compare(Long lhs, Long rhs) { Integer count1 = stickersUseHistory.get(lhs); Integer count2 = stickersUseHistory.get(rhs); if (count1 == null) { count1 = 0; } if (count2 == null) { count2 = 0; } if (count1 > count2) { return -1; } else if (count1 < count2) { return 1; } return 0; } }); preferences.edit().remove("stickers").commit(); saveRecentStickers(); } else { str = preferences.getString("stickers2", ""); String[] args = str.split(","); for (int a = 0; a < args.length; a++) { if (args[a].length() == 0) { continue; } long id = Utilities.parseLong(args[a]); if (id != 0) { newRecentStickers.add(id); } } } sortStickers(); updateStickerTabs(); } catch (Exception e) { FileLog.e("tmessages", e); } } }
From source file:com.scooter1556.sms.android.service.MediaService.java
@RequiresApi(api = Build.VERSION_CODES.O) @Override//from w w w .j a v a 2 s .com public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate()"); restService = RESTService.getInstance(); // Retrieve preferences if they exist SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Load default settings PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Initialise database ConnectionDatabase db = new ConnectionDatabase(this); // Check connection long id = sharedPreferences.getLong("Connection", -1); if (id >= 0) { Connection connection = db.getConnection(id); restService.setConnection(connection); isConnected = true; } else { isConnected = false; } queueManager = new QueueManager(getApplicationContext(), new QueueManager.MetadataUpdateListener() { @Override public void onMetadataChanged(MediaMetadataCompat metadata) { Log.d(TAG, "onMetadataChanged()"); mediaSession.setMetadata(metadata); } @Override public void onMetadataRetrieveError() { Log.d(TAG, "onMetadataRetrieveError()"); playbackManager.updatePlaybackState(getString(R.string.error_no_metadata)); } @Override public void onCurrentQueueIndexUpdated(int queueIndex) { Log.d(TAG, "onCurrentQueueIndexUpdated(" + queueIndex + ")"); playbackManager.handlePlayRequest(); } @Override public void onQueueUpdated(List<MediaSessionCompat.QueueItem> newQueue) { Log.d(TAG, "onQueueUpdated()"); mediaSession.setQueue(newQueue); mediaSession.setQueueTitle("Now Playing"); } }); // Initialise playback manager playbackManager = PlaybackManager.getInstance(); playbackManager.initialise(getApplicationContext(), this, queueManager); // Start a new Media Session mediaSession = new MediaSessionCompat(this, MediaService.class.getSimpleName()); mediaSession.setCallback(playbackManager.getMediaSessionCallback()); mediaSession.setFlags( MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS); Context context = getApplicationContext(); Intent intent = new Intent(context, NowPlayingActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT); mediaSession.setSessionActivity(pendingIntent); mediaSessionExtras = new Bundle(); AutoUtils.setSlotReservationFlags(mediaSessionExtras, true, true, true); mediaSession.setExtras(mediaSessionExtras); setSessionToken(mediaSession.getSessionToken()); try { mediaNotificationManager = new MediaNotificationManager(this); } catch (RemoteException e) { throw new IllegalStateException("Could not create a MediaNotificationManager", e); } if (!TVUtils.isTvUiMode(this)) { castSessionManager = CastContext.getSharedInstance(this).getSessionManager(); castSessionManagerListener = new CastSessionManagerListener(); castSessionManager.addSessionManagerListener(castSessionManagerListener, CastSession.class); } mediaRouter = MediaRouter.getInstance(getApplicationContext()); registerCarConnectionReceiver(); // Register connectivity receiver IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); this.registerReceiver(connectivityChangeReceiver, intentFilter); }