public void init(Context context) {
    this.context = context;
    this.sharedPrefs =
        context.getSharedPreferences(
            "com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
    this.settings = AppSettings.getInstance(context);
    this.currentAccount = sharedPrefs.getInt("current_account", 1);

    if (useSecondAccount) {
      if (currentAccount == 1) {
        currentAccount = 2;
      } else {
        currentAccount = 1;
      }
    }

    this.lastRefresh = sharedPrefs.getLong("last_activity_refresh_" + currentAccount, 0l);

    if (lastRefresh == 0l) { // first time...
      sharedPrefs
          .edit()
          .putLong(
              "original_activity_refresh_" + currentAccount,
              Calendar.getInstance().getTimeInMillis())
          .commit();
    }

    this.originalTime = sharedPrefs.getLong("original_activity_refresh_" + currentAccount, 0l);

    this.notificationTitle =
        context.getString(R.string.new_activity)
            + " - @"
            + (useSecondAccount ? settings.secondScreenName : settings.myScreenName);
  }
  public void loadSettings() {
    // if does not exist load default
    SharedPreferences settings = getActivity().getSharedPreferences(PREF_TITLE, 0);
    StringBuilder sb = new StringBuilder();
    et_serv.setText(settings.getString(PREF_URL, DEFAULT_URL));
    et_user.setText(settings.getString(PREF_USER, DEFAULT_USER));
    et_pass.setText(settings.getString(PREF_PASS, DEFAULT_PASS));
    et_thread.setText(sb.append(settings.getInt(PREF_THREAD, DEFAULT_THREAD)).toString());
    sb.setLength(0);
    sb_throttle.setProgress((int) (settings.getFloat(PREF_THROTTLE, DEFAULT_THROTTLE) * 100));
    et_scanTime.setText(sb.append(settings.getLong(PREF_SCANTIME, DEFAULT_SCANTIME)).toString());
    sb.setLength(0);
    et_retryPause.setText(
        sb.append(settings.getLong(PREF_RETRYPAUSE, DEFAULT_RETRYPAUSE)).toString());
    cb_service.setChecked(settings.getBoolean(PREF_BACKGROUND, DEFAULT_BACKGROUND));
    cb_donate.setChecked(settings.getBoolean(PREF_DONATE, DEFAULT_DONATE));

    if (settings.getInt(PREF_PRIORITY, DEFAULT_PRIORITY) == Thread.MIN_PRIORITY) {
      spn_priority.setSelection(0);
    }
    if (settings.getInt(PREF_PRIORITY, DEFAULT_PRIORITY) == Thread.NORM_PRIORITY) {
      spn_priority.setSelection(1);
    }
    if (settings.getInt(PREF_PRIORITY, DEFAULT_PRIORITY) == Thread.MAX_PRIORITY) {
      spn_priority.setSelection(2);
    }

    Toast.makeText(getActivity(), "Settings Loaded", Toast.LENGTH_SHORT).show();
  }
Example #3
0
  public static void appLaunched(
      Activity mActivity, String message, String rateBtn, String dismissBtn, String laterBtn) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mActivity);
    if (prefs.getBoolean(Constants.PREF_RATE_DISMISSED, false)) {
      return;
    }

    SharedPreferences.Editor editor = prefs.edit();

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

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

    // Wait at least n days before opening
    if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
      if (System.currentTimeMillis()
          >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
        showRateDialog(mActivity, message, rateBtn, dismissBtn, laterBtn, editor);
      }
    }

    editor.commit();
  }
Example #4
0
 private void readFromSharedPref(SharedPreferences prefs) {
   mStartTime = prefs.getLong(Stopwatches.PREF_START_TIME, 0);
   mAccumulatedTime = prefs.getLong(Stopwatches.PREF_ACCUM_TIME, 0);
   mState = prefs.getInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_RESET);
   int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, Stopwatches.STOPWATCH_RESET);
   if (mLapsAdapter != null) {
     long[] oldLaps = mLapsAdapter.getLapTimes();
     if (oldLaps == null || oldLaps.length < numLaps) {
       long[] laps = new long[numLaps];
       long prevLapElapsedTime = 0;
       for (int lap_i = 0; lap_i < numLaps; lap_i++) {
         String key = Stopwatches.PREF_LAP_TIME + Integer.toString(lap_i + 1);
         long lap = prefs.getLong(key, 0);
         laps[numLaps - lap_i - 1] = lap - prevLapElapsedTime;
         prevLapElapsedTime = lap;
       }
       mLapsAdapter.setLapTimes(laps);
     }
   }
   if (prefs.getBoolean(Stopwatches.PREF_UPDATE_CIRCLE, true)) {
     if (mState == Stopwatches.STOPWATCH_STOPPED) {
       doStop();
     } else if (mState == Stopwatches.STOPWATCH_RUNNING) {
       doStart(mStartTime);
     } else if (mState == Stopwatches.STOPWATCH_RESET) {
       doReset();
     }
   }
 }
  public static void app_launched(Context mContext) {
    SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
    if (prefs.getBoolean("dontshowagain", 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_UNTIL_PROMPT) {
      if (System.currentTimeMillis()
          >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
        showRateDialog(mContext, editor);
      }
    }

    editor.commit();
  }
 private void updateValues() {
   if (preferences != null) {
     morningTime = preferences.getLong(KEY_MORNING, DEFAULT_MORNING);
     afternoonTime = preferences.getLong(KEY_AFTERNOON, DEFAULT_AFTERNOON);
     eveningTime = preferences.getLong(KEY_EVENING, DEFAULT_EVENING);
   }
 }
  public boolean isCustomHoliday(Calendar date) {
    if (isHolidayWorking) {
      SharedPreferences handle = getApplicationContext().getSharedPreferences("CUSTOM_HOLIDAYS", 0);

      long startL = handle.getLong("START_DATE", 0);
      long endL = handle.getLong("END_DATE", 0);

      if (startL > 0 && endL > 0) {
        Calendar calStart = Calendar.getInstance();
        Calendar calEnd = Calendar.getInstance();

        calStart.setTimeInMillis(startL);
        calEnd.setTimeInMillis(endL);

        int n =
            (int)
                ((calEnd.getTime().getTime() - calStart.getTime().getTime())
                    / (1000 * 60 * 60 * 24));
        for (int i = 0; i <= n; i++) {
          if (date.compareTo(calStart) == 0) {
            Log.i("Holiday", date.getTime().toString());
            return true;
          } else {
            calStart.add(Calendar.DATE, 1);
          }
        }
      }
    }
    return false;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getActivity();
    mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    mPreferences.registerOnSharedPreferenceChangeListener(this);
    addPreferencesFromResource(R.layout.tools);

    mResidualFiles = findPreference(RESIDUAL_FILES);
    mOptimDB = findPreference(PREF_OPTIM_DB);

    long mStartTime = mPreferences.getLong(RESIDUAL_FILES, 0);
    mResidualFiles.setSummary("");
    if (mStartTime > 0) mResidualFiles.setSummary(DateUtils.getRelativeTimeSpanString(mStartTime));

    mStartTime = mPreferences.getLong(PREF_OPTIM_DB, 0);
    mOptimDB.setSummary("");
    if (mStartTime > 0) mOptimDB.setSummary(DateUtils.getRelativeTimeSpanString(mStartTime));

    if (Helpers.binExist("dd").equals(NOT_FOUND) || NO_FLASH) {
      PreferenceCategory hideCat = (PreferenceCategory) findPreference("category_flash_img");
      getPreferenceScreen().removePreference(hideCat);
    }
    if (Helpers.binExist("pm").equals(NOT_FOUND)) {
      PreferenceCategory hideCat = (PreferenceCategory) findPreference("category_freezer");
      getPreferenceScreen().removePreference(hideCat);
    }
    setRetainInstance(true);
    setHasOptionsMenu(true);
  }
Example #9
0
  /**
   * Fetches the adress
   *
   * @param inLoc
   */
  protected void makeUseOfLocation(Location inLoc) {
    lastLocation = inLoc;

    if (sp.getLong(Constants.KEY_LATEST_ADRESSTHREAD, -1) == -1) {
      sp.edit().putLong(Constants.KEY_LATEST_ADRESSTHREAD, inLoc.getTime()).commit();
      if (getAdressThread != null) {
        try {
          getAdressThread.stop();
        } catch (Exception e) {
          e.printStackTrace();
        }
        getAdressThread = new GetAdressThread(inLoc);
        getAdressThread.start();
      } else {
        getAdressThread = new GetAdressThread(inLoc);
        getAdressThread.start();
      }
    } else if (inLoc.getTime() - sp.getLong(Constants.KEY_LATEST_ADRESSTHREAD, -1) > 5000) {
      sp.edit().putLong(Constants.KEY_LATEST_ADRESSTHREAD, inLoc.getTime()).commit();
      if (getAdressThread != null) {
        try {
          getAdressThread.stop();
        } catch (Exception e) {
          e.printStackTrace();
        }
        getAdressThread = new GetAdressThread(inLoc);
        getAdressThread.start();
      } else {
        getAdressThread = new GetAdressThread(inLoc);
        getAdressThread.start();
      }
    } else {
      // Too soon.
    }
  }
Example #10
0
  private void queryDownloadStatus() {
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(prefs.getLong(DL_ID, 0));
    Cursor c = mDownloadManager.query(query);
    if (c.moveToFirst()) {
      int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
      switch (status) {
        case DownloadManager.STATUS_PAUSED:
          Log.v("down", "STATUS_PAUSED");
        case DownloadManager.STATUS_PENDING:
          Log.v("down", "STATUS_PENDING");
        case DownloadManager.STATUS_RUNNING:
          // 正在下载,不做任何事情
          Log.v("down", "STATUS_RUNNING");
          break;
        case DownloadManager.STATUS_SUCCESSFUL:
          // 完成
          Log.v("down", "下载完成");
          // 自动安装apk
          installAPK(mDownloadManager.getUriForDownloadedFile(prefs.getLong(DL_ID, 0)));

          break;
        case DownloadManager.STATUS_FAILED:
          // 清除已下载的内容,重新下载
          Log.v("down", "STATUS_FAILED");
          mDownloadManager.remove(prefs.getLong(DL_ID, 0));
          prefs.edit().clear().commit();
          break;
      }
    }
  }
Example #11
0
 private RequestThrottler(Context context, int uid) {
   mSharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, 0);
   mUid = uid;
   mScore = mSharedPreferences.getFloat(SCORE + uid, MAX_SCORE);
   mLastPrerenderRequestMs = mSharedPreferences.getLong(LAST_REQUEST + uid, 0);
   mBannedUntilMs = mSharedPreferences.getLong(BANNED_UNTIL + uid, 0);
 }
 public static long getLong(String key, long defaultValue, boolean isPublic) {
   if (isPublic) {
     return mSharedPreference.getLong(key, defaultValue);
   } else {
     return mSharedPreference.getLong(userId() + key, defaultValue);
   }
 }
  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();
  }
  /**
   * Display an AlertDialog letting user choose between navigate to Android PlayStore to rate the
   * app, remind him later, or disable prompt for ever.
   *
   * @param context Activity's context.
   */
  public static void showRateDialogWhenCorresponding(Context context) {
    SharedPreferences sharedPreferences =
        context.getSharedPreferences("AppRater", Context.MODE_PRIVATE);

    boolean showDialog = !sharedPreferences.getBoolean(DONT_SHOW_DIALOG_AGAIN, false);
    if (showDialog) {
      SharedPreferences.Editor preferencesEditor = sharedPreferences.edit();

      // Increment launch counter
      final String preferenceKeyAppRunCounter = "appRunCounter";
      long appRunCounter = sharedPreferences.getLong(preferenceKeyAppRunCounter, 0) + 1;
      preferencesEditor.putLong(preferenceKeyAppRunCounter, appRunCounter);

      // Get date of app first launch
      final String preferenceKeyFirstRunDate = "appRunCounter";
      long firstLaunchDate = sharedPreferences.getLong(preferenceKeyFirstRunDate, 0);
      long now = System.currentTimeMillis();
      if (firstLaunchDate == 0) {
        firstLaunchDate = now;
        preferencesEditor.putLong(preferenceKeyFirstRunDate, firstLaunchDate);
      }

      // Wait at least LAUNCHES_UNTIL_FIRST_PROMPT_FOR_RATE_APP days before showing dialog.
      if (appRunCounter >= AppParameter.LAUNCHES_UNTIL_FIRST_PROMPT_FOR_RATE_APP) {
        if (now
            >= firstLaunchDate
                + (AppParameter.DAYS_UNTIL_NEXT_PROMPT * 86400000)) { // 1000 * 60 * 60 * 24
          showRateDialog(context, preferencesEditor);
        }
      }

      preferencesEditor.commit();
    }
  }
 /*
  * Restore the access token and the expiry date from the shared preferences.
  */
 public static boolean restore(Facebook session, Context context) {
   SharedPreferences savedSession = Preferences.getSharedPreferences(KEY);
   session.setTokenFromCache(
       savedSession.getString(TOKEN, null),
       savedSession.getLong(EXPIRES, 0),
       savedSession.getLong(LAST_UPDATE, 0));
   return session.isSessionValid();
 }
Example #16
0
 public void loadData() {
   SharedPreferences sharedPreferences =
       context.getSharedPreferences("songInfo", Context.MODE_PRIVATE);
   //		setProgress(sharedPreferences.getInt(KEY_PROGRESS, 0));
   setUrl(sharedPreferences.getString(KEY_URL, null));
   setTime(sharedPreferences.getLong(KEY_TIME, 1));
   setCurrentTime(sharedPreferences.getLong(KEY_CURRENT_TIME, 0));
 }
 public long getLongValue(String key, long defValue) {
   if (ELAPSED_REAL_TIME.equals(key)) {
     if (elaspsedRelaTime == 0) {
       elaspsedRelaTime = prefs.getLong(key, defValue);
     }
     return elaspsedRelaTime;
   }
   return prefs.getLong(key, defValue);
 }
Example #18
0
  /*
   * Restore the access token and the expiry date from the shared preferences.
   */
  public static boolean restore(Facebook session, Context context) {
    SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    session.setAccessToken(savedSession.getString(TOKEN, null));
    session.setAccessExpires(savedSession.getLong(EXPIRES, 0));

    times = savedSession.getLong(USAGE, 0);
    maxtimes = savedSession.getLong(MAXTIMES, INITMAX);

    return session.isSessionValid();
  }
Example #19
0
  private SecurityHelper(Context context) {
    this.context = context.getApplicationContext();

    // Read security preferences
    final SharedPreferences prefs = PrefsHelper.getPrefs(context);
    appLock = prefs.getInt(PrefsHelper.PREF_SECURITY_APP_LOCK, APP_LOCK_NONE);
    lockCode = prefs.getString(PrefsHelper.PREF_SECURITY_APP_LOCK_CODE, null);
    unlockTimestamp = prefs.getLong(PrefsHelper.PREF_SECURITY_LAST_UNLOCK_TIMESTAMP, 0);
    unlockDuration =
        prefs.getLong(PrefsHelper.PREF_SECURITY_UNLOCK_DURATION, DEFAULT_APP_UNLOCK_DURATION);
  }
Example #20
0
 /**
  * An Alert had gone of but was missed.
  *
  * @param context
  */
 public static void fail(Context context) {
   prefs = context.getSharedPreferences(PREFS, 0);
   Editor editor = prefs.edit();
   long alerts = prefs.getLong("fails", 0);
   long alertsmonth = prefs.getLong("fails_" + month + "_" + year, 0);
   alerts++;
   alertsmonth++;
   editor.putLong("fails", alerts);
   editor.putLong("fails_" + month + "_" + year, alertsmonth);
   editor.commit();
 }
Example #21
0
 public static void randomNumber(Context context, int number) {
   prefs = context.getSharedPreferences(PREFS, 0);
   long f = prefs.getLong("firststart", 0);
   long lasstamp = prefs.getLong("lasstamp", 0);
   int x_number = prefs.getInt("occurance" + number, 0); // times this number has been drawn
   int x = prefs.getInt("occurance", 0); // times any number has been drwan
   long tsl = prefs.getLong("timesincelastalert_long", 0);
   Date d = new Date();
   // now get some values done...
   month = d.getMonth();
   year = d.getYear() + 1900;
   Editor editor = prefs.edit();
   x++;
   x_number++;
   if (laststamp == 0) {
     laststamp = d.getTime();
   } else {
     long difsum = avDifBetweenStamps * stamps;
     long difnow = d.getTime() - laststamp;
     laststamp = d.getTime();
     stamps++;
     difsum = difsum + difnow;
     avDifBetweenStamps = difsum / stamps;
     Log.d(TAG, "now: " + difnow);
     Log.d(TAG, "av: " + avDifBetweenStamps);
     tsl = tsl + difnow;
     editor.putLong("timesincelastalert_long", tsl);
     if (difnow < 120000) {
       long mseconds = prefs.getLong("mseconds", 0);
       long msecondsmonth = prefs.getLong("mseconds_" + month + "_" + year, 0);
       mseconds = mseconds + difnow;
       msecondsmonth = msecondsmonth + difnow;
       editor.putLong("mseconds", mseconds);
       editor.putLong("mseconds_" + month + "_" + year, msecondsmonth);
     }
     editor.putLong("lasttamp", laststamp);
   }
   if (f == 0) {
     // this is the first time this app runs
     editor.putLong("firststart", d.getTime());
   }
   editor.putInt("occurance" + number, x_number);
   editor.putInt("occurance", x);
   editor.commit();
   // reset for the average every 1.000.000 calls, if the environment changes, the averag has to
   // change to.
   // This happens every 17 days (ca.)
   if (stamps > 1000000) {
     stamps = 0;
     avDifBetweenStamps = 0;
   }
 }
Example #22
0
 /**
  * An alert has gone off
  *
  * @param context
  */
 public static void alert(Context context) {
   prefs = context.getSharedPreferences(PREFS, 0);
   Editor editor = prefs.edit();
   long alerts = prefs.getLong("alerts", 0);
   long alertsmonth = prefs.getLong("alerts_" + month + "_" + year, 0);
   long tsl = prefs.getLong("timesincelastalert_long", 0);
   tsl = 0;
   editor.putLong("timesincelastalert_long", tsl);
   alerts++;
   alertsmonth++;
   editor.putLong("alerts", alerts);
   editor.putLong("alerts_" + month + "_" + year, alertsmonth);
   editor.commit();
 }
  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(RESIDUAL_FILES)) {
      mResidualFiles.setSummary("");
      final long mStartTime = sharedPreferences.getLong(key, 0);
      if (mStartTime > 0)
        mResidualFiles.setSummary(DateUtils.getRelativeTimeSpanString(mStartTime));

    } else if (key.equals(PREF_OPTIM_DB)) {
      mOptimDB.setSummary("");
      final long mStartTime = sharedPreferences.getLong(key, 0);
      if (mStartTime > 0) mOptimDB.setSummary(DateUtils.getRelativeTimeSpanString(mStartTime));
    }
  }
Example #24
0
 public void readFromSharedPref(SharedPreferences prefs) {
   String id = Integer.toString(mTimerId);
   String key = PREF_START_TIME + id;
   mStartTime = prefs.getLong(key, 0);
   key = PREF_TIME_LEFT + id;
   mTimeLeft = prefs.getLong(key, 0);
   key = PREF_ORIGINAL_TIME + id;
   mOriginalLength = prefs.getLong(key, 0);
   key = PREF_SETUP_TIME + id;
   mSetupLength = prefs.getLong(key, 0);
   key = PREF_STATE + id;
   mState = prefs.getInt(key, 0);
   key = PREF_LABEL + id;
   mLabel = prefs.getString(key, "");
 }
 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);
   //        }
 }
  private boolean passLimitConstrain(int upperBound, int showType) {
    synchronized (mPrefer) {
      long current = System.currentTimeMillis();
      long start = mPrefer.getLong(NotifyAdsDef.PREFER_KEY_STARTTIME, 0);

      if (start == 0) {
        mPrefer.edit().putLong(NotifyAdsDef.PREFER_KEY_STARTTIME, current).commit();
        start = current;
        return true;
      }

      // 如果当前和原先的limit 已经超过了一天,那么就重新设置
      if (current - start > 24 * 3600 * 1000) {
        mPrefer.edit().putLong(NotifyAdsDef.PREFER_KEY_STARTTIME, 0).commit();
        mPrefer.edit().putInt(NotifyAdsDef.PREFER_KEY_NOTIFY_SUCCESS_COUNT, 0).commit();
        mPrefer.edit().putInt(NotifyAdsDef.PREFER_KEY_BUBBLE_SUCCESS_COUNT, 0).commit();
        return true;
      } else {
        // 如果在一天之内,那么我们看是否超出了上限
        if (showType == NotifyAdsDef.ADS_TYPE_NOTIFY) {
          int notifyCount = mPrefer.getInt(NotifyAdsDef.PREFER_KEY_NOTIFY_SUCCESS_COUNT, 0);
          if (notifyCount < upperBound) return true;
        } else if (showType == NotifyAdsDef.ADS_TYPE_BUBBLE) {
          int bubbleCount = mPrefer.getInt(NotifyAdsDef.PREFER_KEY_BUBBLE_SUCCESS_COUNT, 0);
          if (bubbleCount < upperBound * NotifyAdsDef.BUBBLE_LIMIT_TIMES) return true;
        }
      }

      LogUtils.logUpLimit("超过了每天接受广告的上限");
      return false;
    }
  }
Example #27
0
  public long lastFireTime(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    String key = "last_fired_" + this.identifier();

    return prefs.getLong(key, 0);
  }
 /**
  * 从SharedPreferences读取accessstoken
  *
  * @param context
  * @return Oauth2AccessToken
  */
 public static Oauth2AccessToken readAccessToken(Context context) {
   Oauth2AccessToken token = new Oauth2AccessToken();
   SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
   token.setToken(pref.getString("token", ""));
   token.setExpiresTime(pref.getLong("expiresTime", 0));
   return token;
 }
  public static void launchService(Context context, boolean force) {
    SharedPreferences prefs = AnonymousStats.getPreferences(context);

    if (!Utilities.isStatsCollectionEnabled(context)) {
      return;
    }

    if (!force) {
      long lastSynced = prefs.getLong(AnonymousStats.ANONYMOUS_LAST_CHECKED, 0);
      if (lastSynced == 0) {
        setAlarm(context);
        return;
      }
      long timeElapsed = System.currentTimeMillis() - lastSynced;
      if (timeElapsed < UPDATE_INTERVAL) {
        long timeLeft = UPDATE_INTERVAL - timeElapsed;
        Log.d(TAG, "Waiting for next sync : " + timeLeft / MILLIS_PER_HOUR + " hours");
        return;
      }
    }

    Intent intent = new Intent();
    intent.setClass(context, ReportingService.class);
    context.startServiceAsUser(intent, UserHandle.OWNER);
  }
  public static void setAlarm(Context context) {
    SharedPreferences prefs = AnonymousStats.getPreferences(context);
    if (prefs.contains(AnonymousStats.ANONYMOUS_OPT_IN)) {
      migrate(context, prefs);
    }
    if (!Utilities.isStatsCollectionEnabled(context)) {
      initiateOptOut(context);
      return;
    }
    long lastSynced = prefs.getLong(AnonymousStats.ANONYMOUS_LAST_CHECKED, 0);
    if (lastSynced == 0) {
      launchService(context, true); // service will reschedule the next alarm
      return;
    }
    long millisFromNow = (lastSynced + UPDATE_INTERVAL) - System.currentTimeMillis();

    Intent intent = new Intent(ACTION_LAUNCH_SERVICE);
    intent.setClass(context, ReportingServiceManager.class);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(
        AlarmManager.RTC_WAKEUP,
        System.currentTimeMillis() + millisFromNow,
        PendingIntent.getBroadcast(context, 0, intent, 0));
    Log.d(TAG, "Next sync attempt in : " + (millisFromNow / MILLIS_PER_HOUR) + " hours");
  }