Ejemplo n.º 1
1
    @Override
    public boolean onContextItemSelected(MenuItem item) {

      int posn = (int) ((AdapterContextMenuInfo) item.getMenuInfo()).position;
      Codec c = codecs.elementAt(posn);
      if (item.getItemId() == MENU_UP) {
        if (posn == 0) return super.onContextItemSelected(item);
        Codec tmp = codecs.elementAt(posn - 1);
        codecs.set(posn - 1, c);
        codecs.set(posn, tmp);
      } else if (item.getItemId() == MENU_DOWN) {
        if (posn == codecs.size() - 1) return super.onContextItemSelected(item);
        Codec tmp = codecs.elementAt(posn + 1);
        codecs.set(posn + 1, c);
        codecs.set(posn, tmp);
      }
      PreferenceScreen ps = getPreferenceScreen();
      SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
      String v = "";
      SharedPreferences.Editor e = sp.edit();

      for (Codec d : codecs) v = v + d.number() + " ";
      e.putString(Settings.PREF_CODECS, v);
      e.commit();
      ps.removeAll();
      addPreferences(ps);
      return super.onContextItemSelected(item);
    }
Ejemplo n.º 2
0
 @Override
 public void onPause() {
   super.onPause();
   mTestSP.unregisterOnSharedPreferenceChangeListener(mTestCardListener);
   mFoodSP.unregisterOnSharedPreferenceChangeListener(mFoodCardListener);
   mPoolSP.unregisterOnSharedPreferenceChangeListener(mPoolCardListener);
 }
Ejemplo n.º 3
0
  public static void check() {
    HashMap<String, String> old = new HashMap<String, String>(codecs.size());

    for (Codec c : codecs) {
      c.update();
      old.put(c.name(), c.getValue());
      if (!c.isLoaded()) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
        SharedPreferences.Editor e = sp.edit();

        e.putString(c.key(), "never");
        e.commit();
      }
    }

    for (Codec c : codecs)
      if (!old.get(c.name()).equals("never")) {
        c.init();
        if (c.isLoaded()) {
          SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
          SharedPreferences.Editor e = sp.edit();

          e.putString(c.key(), old.get(c.name()));
          e.commit();
          c.init();
        } else c.fail();
      }
  }
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {

    // Hotkeys
    if (keyCode == KeyEvent.KEYCODE_BACK) {

      // If the new interval != the old interval, we got to restart the
      // "alarm"
      if (originalInterval != sharedPreferences.getInt(Constants.SP_BL_INTERVAL_SERVICE, 0)) {

        // Get the interval
        int serviceInterval =
            sharedPreferences.getInt(
                    Constants.SP_BL_INTERVAL_SERVICE, (Constants.HOUR_IN_SECONDS / 2))
                * 1000;

        // Restart the AlarmManager
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent =
            PendingIntent.getService(this, 0, new Intent(this, BattlelogService.class), 0);
        alarmManager.cancel(pendingIntent);
        alarmManager.setInexactRepeating(
            AlarmManager.ELAPSED_REALTIME, 0, serviceInterval, pendingIntent);

        Log.d(
            Constants.DEBUG_TAG,
            "Setting the service to update every " + serviceInterval / 60000 + " minutes");
      }
      startActivity(new Intent(this, DashboardActivity.class));
      finish();
      return true;
    }

    return super.onKeyDown(keyCode, event);
  }
Ejemplo n.º 5
0
    @Override
    public void run() {
      // check for STORAGE permission
      if (!canWriteToStorage()) return;

      SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(mActivity);
      String driveAccount =
          SP.getString(
              mActivity.getResources().getString(R.string.PROPERTY_googledrive_account),
              "<Not Set>");

      if (driveAccount.equals("<Not Set>")) return;
      GoogleApiClient googleApiClient =
          new GoogleApiClient.Builder(mActivity)
              .addApi(Drive.API)
              .addScope(Drive.SCOPE_FILE)
              .setAccountName(driveAccount)
              .addConnectionCallbacks(m_me)
              .addOnConnectionFailedListener(m_me)
              .build();

      googleApiClient.blockingConnect();
      if (!googleApiClient.isConnected()) return;

      if (mTeamNumber >= 0) {
        syncPhotosForTeam(googleApiClient, mTeamNumber);
      } else {
        mRequester = null;

        // TODO: loop over all folders in the photos dir
      }
    }
  public static void app_launched(Context context, int days, int launches) {

    SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME, 0);

    // Check if app was already rated
    if (prefs.getBoolean("rated", false)) {
      return;
    }

    SharedPreferences.Editor editor = prefs.edit();

    // Increment launch counter
    long launch_count = prefs.getLong("launch_count", 0) + 1;
    editor.putLong("launch_count", launch_count);

    // Get date of first launch
    Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
    if (date_firstLaunch == 0) {
      date_firstLaunch = System.currentTimeMillis();
      editor.putLong("date_firstlaunch", date_firstLaunch);
    }

    // Wait at least n days before opening
    if (launch_count >= launches) {
      if (System.currentTimeMillis() >= date_firstLaunch + (days * 24 * 60 * 60 * 1000)) {
        showRateDialog(context, editor);
      }
    }

    editor.commit();
  }
 public void refreshWeather(int flag, boolean isAuto, boolean broadcast) {
   if (!Help.networkState(mContext) && !broadcast) {
     Log.d(TAG, "network is disabled");
     return;
   }
   SharedPreferences preferences =
       mContext.getSharedPreferences("controller", Context.MODE_PRIVATE);
   long lastTime = preferences.getLong("last_time_fetch_datas", 0);
   boolean isSuccess = preferences.getBoolean("update_success", true);
   if (System.currentTimeMillis() - lastTime > 1000 * 3600 * 2) {
     updateWeather(flag, preferences);
   } else if (System.currentTimeMillis() - lastTime <= 1000 * 3600 * 2 && isSuccess && !isAuto) {
     Toast.makeText(
             mContext,
             "It's unnecessary to update so frequently. Updating every 2h maybe is better.",
             Toast.LENGTH_SHORT)
         .show();
   } else if (System.currentTimeMillis() - lastTime <= 1000 * 10 && !isSuccess && !isAuto) {
     Toast.makeText(
             mContext, "Last update was fail. Just wait another ten second!", Toast.LENGTH_SHORT)
         .show();
   } else if (System.currentTimeMillis() - lastTime > 1000 * 10 && !isSuccess) {
     updateWeather(flag, preferences);
   } else if (System.currentTimeMillis() - lastTime > 1000 * 3600 * 3 && broadcast) {
     updateWeather(flag, preferences);
   }
   //        else if (broadcast && System.currentTimeMillis() - lastTime > 1000 * 3600 * 2) {
   //            updateWeather(flag, preferences);
   //        }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get instances to upload
    Intent i = getIntent();
    ArrayList<String> instances = i.getStringArrayListExtra(GlobalConstants.KEY_INSTANCES);
    if (instances == null) {
      // nothing to upload
      return;
    }

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String url = settings.getString(UserPreferences.KEY_SERVER, getString(R.string.default_server));
    String authCredentials =
        settings.getString(UserPreferences.KEY_USERNAME, getString(R.string.username))
            + ":"
            + settings.getString(UserPreferences.KEY_PASSWORD, getString(R.string.password));

    mInstanceUploaderTask = (InstanceUploaderTask) getLastNonConfigurationInstance();
    if (mInstanceUploaderTask == null) {

      // setup dialog and upload task
      showDialog(PROGRESS_DIALOG);
      mInstanceUploaderTask = new InstanceUploaderTask();
      mInstanceUploaderTask.setUploadServer(url + "/fileUpload?");
      mInstanceUploaderTask.setAuthCredentials(authCredentials);
      totalCount = instances.size();

      // convert array list to an array
      String[] sa = instances.toArray(new String[totalCount]);
      mInstanceUploaderTask.execute(sa);
    }
  }
Ejemplo n.º 9
0
 public static boolean getBoolean(String key, boolean defaultValue, boolean isPublic) {
   if (isPublic) {
     return mSharedPreference.getBoolean(key, defaultValue);
   } else {
     return mSharedPreference.getBoolean(userId() + key, defaultValue);
   }
 }
Ejemplo n.º 10
0
 public static String getString(String key, String defaultValue, boolean isPublic) {
   if (isPublic) {
     return mSharedPreference.getString(key, defaultValue);
   } else {
     return mSharedPreference.getString(userId() + key, defaultValue);
   }
 }
 /**
  * Reads the photo strip template preference.
  *
  * @param context the {@link Context}.
  * @return the stored {@link PhotoStripTemplate}.
  */
 public PhotoStripTemplate getPhotoStripTemplate(Context context) {
   SharedPreferences preferences =
       PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
   String template =
       preferences.getString(KEY_PHOTO_STRIP_TEMPLATE, PhotoStripTemplate.VERTICAL_3.name());
   return PhotoStripTemplate.valueOf(template);
 }
 /**
  * Reads the photo booth theme preference.
  *
  * @param context the {@link Context}.
  * @return the stored {@link PhotoBoothTheme}.
  */
 public PhotoBoothTheme getPhotoBoothTheme(Context context) {
   SharedPreferences preferences =
       PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
   String theme =
       preferences.getString(KEY_PHOTO_BOOTH_THEME, PhotoBoothTheme.STRIPES_BLUE.name());
   return PhotoBoothTheme.valueOf(theme);
 }
Ejemplo n.º 13
0
  @Override
  public void onCreate() {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mLBM = LocalBroadcastManager.getInstance(this);

    mLogger.info("WalletService created");

    mApp = (WalletApplication) getApplicationContext();

    mContext = getApplicationContext();
    mRes = mContext.getResources();

    mTimeoutWorker = Executors.newSingleThreadScheduledExecutor();

    final String lockName = getPackageName() + " blockchain sync";
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    String fiatRateSource = mPrefs.getString(SettingsActivity.KEY_FIAT_RATE_SOURCE, "");
    setFiatRateSource(fiatRateSource);

    // Register for future preference changes.
    mPrefs.registerOnSharedPreferenceChangeListener(this);

    // Register with the WalletApplication.
    mApp.setWalletService(this);
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    if (id == R.id.action_logout) {

      SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
      String name = sharedPreferences.getString("username", "ab");

      Editor editor = sharedPreferences.edit();

      Toast.makeText(SearchLoggedInActivity.this, "Goodbye " + name, Toast.LENGTH_LONG).show();

      editor.clear();
      editor.commit();

      Intent intent = new Intent(SearchLoggedInActivity.this, MainActivity.class);
      startActivity(intent);
      finish();
    }
    return super.onOptionsItemSelected(item);
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // Retrieve preferences
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    isBalanced = sp.getBoolean(MainActivity.CHECKBOX_BALANCE, false);

    // Get and initialize views
    View v = inflater.inflate(R.layout.control, container, false);
    textViewLevel = (TextView) v.findViewById(R.id.textView_level);
    textViewLevelRight = (TextView) v.findViewById(R.id.textView_levelRight);
    seekBarMain = (SeekBar) v.findViewById(R.id.seekBar_main);
    seekBarMainRight = (SeekBar) v.findViewById(R.id.seekBar_mainRight);
    CheckBox checkBoxBalance = (CheckBox) v.findViewById(R.id.checkBox_Balance);
    checkBoxBalance.setChecked(isBalanced);

    // Set view listeners
    seekBarMain.setOnSeekBarChangeListener(this);
    seekBarMainRight.setOnSeekBarChangeListener(this);
    checkBoxBalance.setOnCheckedChangeListener(this);

    rebuildSeekbar();

    // Set up idle kill timer
    idleKillTimer = new Handler(); // Make your Main UIWorker Thread to execute this statement
    idleTimerRunnable = new IdleTimer();
    if (getActivity().getClass() == DialogActivity.class) {
      idleKillTimer.postDelayed(idleTimerRunnable, FINISH_DELAY);
    }

    return v;
  }
Ejemplo n.º 16
0
 public void deleteFromSharedPref(SharedPreferences prefs) {
   SharedPreferences.Editor editor = prefs.edit();
   String key = PREF_TIMER_ID + Integer.toString(mTimerId);
   String id = Integer.toString(mTimerId);
   editor.remove(key);
   key = PREF_START_TIME + id;
   editor.remove(key);
   key = PREF_TIME_LEFT + id;
   editor.remove(key);
   key = PREF_ORIGINAL_TIME + id;
   editor.remove(key);
   key = PREF_SETUP_TIME + id;
   editor.remove(key);
   key = PREF_STATE + id;
   editor.remove(key);
   Set<String> timersList = prefs.getStringSet(PREF_TIMERS_LIST, new HashSet<String>());
   timersList.remove(id);
   editor.putStringSet(PREF_TIMERS_LIST, timersList);
   key = PREF_LABEL + id;
   editor.remove(key);
   key = PREF_DELETE_AFTER_USE + id;
   editor.remove(key);
   editor.commit();
   // dumpTimersFromSharedPrefs(prefs);
 }
Ejemplo n.º 17
0
  @Override
  public void onReceive(Context context, Intent intent) {

    Log.i("WifiO", "RecvTempDisable");

    LogWO logg = new LogWO(context);
    logg.log("WifiOpti Service disabled for 5m");

    SharedPreferences sett = context.getSharedPreferences("WifiOpti", 2);
    SharedPreferences.Editor settEditor = sett.edit();

    settEditor.putBoolean("WifiOptiServiced", false);
    settEditor.putBoolean("WifiOptiTempDisabled", true);
    settEditor.commit();

    // Turn off service
    Intent serviceIntent = new Intent(context, WifiOptiService.class);
    context.stopService(serviceIntent);

    // Schedule restart
    Intent alarmIntent = new Intent(context, RecvTempResume.class);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.add(Calendar.MINUTE, 5);

    Log.d("WifiO", " -> " + cal.getTime().toString());

    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
  }
Ejemplo n.º 18
0
 public static float getFloat(String key, float defaultValue, boolean isPublic) {
   if (isPublic) {
     return mSharedPreference.getFloat(key, defaultValue);
   } else {
     return mSharedPreference.getFloat(userId() + key, defaultValue);
   }
 }
  private void useTheme(final Context context) {
    SharedPreferences preferences =
        context.getSharedPreferences(Theme.PREFS_NAME_THEME_SETTING, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(Theme.PREFS_KEY_PACKAGE_NAME, entry.getPackageName());
    editor.putInt(Theme.PREFS_KEY_RESOURCE_TYPE, Theme.RESOURCES_FROM_APK);
    editor.putString(Theme.PREFS_KEY_THEME_NAME, entry.getName());
    editor.commit();

    Dialog dialog =
        new AlertDialog.Builder(context)
            .setTitle(R.string.title_dialog_alert)
            .setMessage("重启应用皮肤才能生效,确认要退出应用吗?")
            .setPositiveButton(
                R.string.btn_confirm,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    exitApp(context);
                  }
                })
            .setNegativeButton(
                R.string.btn_cancel,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                  }
                })
            .create();
    dialog.show();
  }
Ejemplo n.º 20
0
 public void setShouldBootWithSystem(boolean value) {
   String key = this.getClass().getName();
   SharedPreferences settings = getSharedPreferences(key, 0);
   SharedPreferences.Editor editor = settings.edit();
   editor.putBoolean(SETTING_BOOT_WITH_SYSTEM, value);
   editor.commit();
 }
Ejemplo n.º 21
0
  @Override
  public void onStart() {
    super.onStart();
    // new Handler().postDelayed(new Runnable() {

    //	@Override
    //	public void run() {
    SharedPreferences mPreferences =
        this.getSharedPreferences("RainbowAgriLivePrice", MODE_PRIVATE);
    mobileNumb = mPreferences.getString("coordinatorUserId", null);

    if (mobileNumb != null) {
      System.out.println("the received mobile number is-===" + mobileNumb);
      GetCategoryDetails details = new GetCategoryDetails(this);
      details.execute();
      catagoryFactory.onCreate();

    } else if (mobileNumb == null) {

      System.out.println("the not received mobile number is-===" + mobileNumb);
      Intent signupIntent = new Intent(this, UserAuthMainActivity.class);
      this.startActivity(signupIntent);
      this.finish();
    }
  }
Ejemplo n.º 22
0
  @Override
  public List<byte[]> getKeyHandlesByIssuerAndAppId(String issuer, String application) {
    List<byte[]> result = new ArrayList<byte[]>();

    final SharedPreferences keySettings =
        context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);
    Map<String, String> keyTokens = (Map<String, String>) keySettings.getAll();
    for (Map.Entry<String, String> keyToken : keyTokens.entrySet()) {
      String tokenEntryString = keyToken.getValue();

      TokenEntry tokenEntry = new Gson().fromJson(tokenEntryString, TokenEntry.class);

      if (((issuer == null) || issuer.equals(tokenEntry.getIssuer()))
          && ((application == null) || application.equals(tokenEntry.getApplication()))) {
        String keyHandleKey = keyToken.getKey();
        try {
          byte[] keyHandle = keyToKeyHandle(keyHandleKey);
          result.add(keyHandle);
        } catch (DecoderException ex) {
          Log.e(TAG, "Invalid keyHandle: " + keyHandleKey, ex);
        }
      }
    }
    return result;
  }
Ejemplo n.º 23
0
  /**
   * Constructor
   *
   * @param activity This will be used to fetch string contants for file storage and displaying
   *     toasts. Also, if this is a MainActivity, then this activity's .updateDataSyncLabel() will
   *     be called when a Drive connection either suceeds or fails.
   */
  public FileUtils(Activity activity) {
    mActivity = activity;
    m_me = this;

    // store string constants and preferences in member variables just for cleanliness
    // (since the strings are `static`, when any instances of FileUtils update these, all instances
    // will get the updates)
    SharedPreferences SP =
        PreferenceManager.getDefaultSharedPreferences(mActivity.getBaseContext());
    mRemoteToplevelFolderName = activity.getString(R.string.FILE_TOPLEVEL_DIR);
    mRemoteTeamFolderName =
        SP.getString(
            mActivity.getResources().getString(R.string.PROPERTY_googledrive_teamname),
            "<Not Set>");
    mRemoteEventFolderName =
        SP.getString(
            mActivity.getResources().getString(R.string.PROPERTY_googledrive_event), "<Not Set>");
    mRemoteTeamPhotosFolderName = "Team Photos";

    mLocalToplevelFilePath = "/sdcard/" + mRemoteToplevelFolderName;
    mLocalTeamFilePath = mLocalToplevelFilePath + "/" + mRemoteTeamFolderName;
    mLocalEventFilePath = mLocalTeamFilePath + "/" + mRemoteEventFolderName;
    mLocalTeamPhotosFilePath = mLocalTeamFilePath + "/" + mRemoteTeamPhotosFolderName;

    checkLocalFileStructure();
    reset_mGoogleApiClient();
  }
Ejemplo n.º 24
0
 @Override
 public void deleteTokenEntry(byte[] keyHandle) {
   String keyHandleKey = keyHandleToKey(keyHandle);
   final SharedPreferences keySettings =
       context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);
   keySettings.edit().remove(keyHandleKey).apply(); // commit();
 }
  private void sendResults(Long attemptId) {
    dbHelper = new DbHelper(this);
    Cursor cur = dbHelper.getUnsubmitted(attemptId.intValue());
    cur.moveToFirst();
    String content = "";
    while (cur.isAfterLast() == false) {
      content = dbHelper.createSubmitResponseObject(cur);
      cur.moveToNext();
    }
    cur.close();
    dbHelper.close();

    APIRequest[] resultsToSend = new APIRequest[1];
    APIRequest r = new APIRequest();
    r.fullurl =
        prefs.getString("prefServer", getString(R.string.prefServerDefault))
            + "api/?method=submit&format=json";
    r.rowId = attemptId.intValue();
    r.username = prefs.getString("prefUsername", "");
    r.password = prefs.getString("prefPassword", "");
    r.timeoutConnection = Integer.parseInt(prefs.getString("prefServerTimeoutConnection", "10000"));
    r.timeoutSocket = Integer.parseInt(prefs.getString("prefServerTimeoutResponse", "10000"));
    r.content = content;
    resultsToSend[0] = r;

    Toast.makeText(this, "Sending results", Toast.LENGTH_SHORT).show();

    // send results to server
    SubmitResultsTask task = new SubmitResultsTask(QuizActivityEnd.this);
    task.setDownloaderListener(this);
    task.execute(resultsToSend);
  }
Ejemplo n.º 26
0
 @Override
 public void saveLog(LogInfo logInfo) {
   final String logInfoString = new Gson().toJson(logInfo);
   final SharedPreferences logSettings =
       context.getSharedPreferences(LOGS_STORE, Context.MODE_PRIVATE);
   logSettings.edit().putString(UUID.randomUUID().toString(), logInfoString).apply(); // commit();
 }
Ejemplo n.º 27
0
 @Override
 protected void onResume() {
   // TODO 自動生成されたメソッド・スタブ
   super.onResume();
   SharedPreferences pref = getSharedPreferences("preceding", MODE_PRIVATE);
   num2bg(pref.getInt("bgNum", 0));
 }
Ejemplo n.º 28
0
  @Override
  public void storeTokenEntry(byte[] keyHandle, TokenEntry tokenEntry) {
    Boolean isSave = true;
    List<String> tokens = getTokenEntries();
    for (String tokenStr : tokens) {
      TokenEntry token = new Gson().fromJson(tokenStr, TokenEntry.class);
      if (token.getIssuer().equalsIgnoreCase(tokenEntry.getIssuer())) {
        isSave = false;
      }
    }
    if (isSave) {
      String keyHandleKey = keyHandleToKey(keyHandle);

      final String tokenEntryString = new Gson().toJson(tokenEntry);
      if (BuildConfig.DEBUG)
        Log.d(
            TAG,
            "Storing new keyHandle: " + keyHandleKey + " with tokenEntry: " + tokenEntryString);

      final SharedPreferences keySettings =
          context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);

      keySettings.edit().putString(keyHandleKey, tokenEntryString).apply(); // commit();

      final SharedPreferences keyCounts =
          context.getSharedPreferences(U2F_KEY_COUNT_FILE, Context.MODE_PRIVATE);
      keyCounts.edit().putInt(keyHandleKey, 0).apply(); // commit();
    }
  }
Ejemplo n.º 29
0
    public void onComplete(Bundle values) {
      //  Handle a successful login

      String token = this.fba.facebook.getAccessToken();
      long token_expires = this.fba.facebook.getAccessExpires();
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.fba.ctx);
      prefs.edit().putLong("access_expires", token_expires).commit();
      prefs.edit().putString("access_token", token).commit();

      Log.d("FB", "authorized");
      Log.d("PhoneGapLog", values.toString());

      try {
        JSONObject o = new JSONObject(this.fba.facebook.request("/me"));
        this.fba.userId = o.getString("id");
        this.fba.success(getResponse(), this.fba.callbackId);
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  public void testSharedCache()
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidKeySpecException, KeyStoreException, CertificateException, NoSuchProviderException,
          InvalidAlgorithmParameterException, UnrecoverableEntryException, DigestException,
          IllegalBlockSizeException, BadPaddingException, IOException, NameNotFoundException,
          NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    AuthenticationSettings.INSTANCE.setSharedPrefPackageName("mockpackage");
    StorageHelper mockSecure = mock(StorageHelper.class);
    Context mockContext = mock(Context.class);
    Context packageContext = mock(Context.class);
    SharedPreferences prefs = mock(SharedPreferences.class);
    when(prefs.contains("testkey")).thenReturn(true);
    when(prefs.getString("testkey", "")).thenReturn("test_encrypted");
    when(mockSecure.decrypt("test_encrypted")).thenReturn("{\"mClientId\":\"clientId23\"}");
    when(mockContext.createPackageContext("mockpackage", Context.MODE_PRIVATE))
        .thenReturn(packageContext);
    when(packageContext.getSharedPreferences("com.microsoft.aad.adal.cache", Activity.MODE_PRIVATE))
        .thenReturn(prefs);
    Class<?> c = DefaultTokenCacheStore.class;
    Field encryptHelper = c.getDeclaredField("sHelper");
    encryptHelper.setAccessible(true);
    encryptHelper.set(null, mockSecure);
    DefaultTokenCacheStore cache = new DefaultTokenCacheStore(mockContext);
    TokenCacheItem item = cache.getItem("testkey");

    // Verify returned item
    assertEquals("Same item as mock", "clientId23", item.getClientId());
    encryptHelper.set(null, null);
  }