0

I'm trying to implement a time check like this in my app: If the app was ran in the last 5 mins, do this. Else do that.

I did some research on the SharedPreferences class already but I have not found a solution yet. I have never used this before.

PTN
  • 1,658
  • 5
  • 24
  • 54

1 Answers1

1

This should work:

 SharedPreferences pref;

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    pref = PreferenceManager.getDefaultSharedPreferences(this);

}


@Override
protected void onResume() {
    super.onResume();
    long lastRun = pref.getLong("LAST_RUN", -1);
    if (lastRun == -1){
        //first run after install
    } else {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastRun > (1000 * 60 * 5)) {// more than 5 minutes

        } else { // less than 5 minutes

        }
    }
}

@Override
protected void onStop() {
    super.onStop();
    pref.edit().putLong("LAST_RUN", System.currentTimeMillis()).apply();
}
yshahak
  • 4,996
  • 1
  • 31
  • 37
  • Basically off the UI Thread is to more heavy stuff, this task probably determine how the UI should be and need to done fast. – yshahak Aug 09 '15 at 07:49