PTN
PTN

Reputation: 1692

Get last open/close time android

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.

Upvotes: 0

Views: 137

Answers (1)

yshahak
yshahak

Reputation: 5096

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();
}

Upvotes: 1

Related Questions