How to get & ldquo; Last & rdquo; The date or time the user ran the app in Android?

advertisements

How to get the time or a date of a user turning off an application? um Clash of Clans for example, you can see your clan users' last visiting time or last turning off time of the application. such as "5 minutes ago", or "1 day, 3 hours ago"

i just want to know the specific method name of this and look for it at google android references.


There is no specific method for this, you can get the systems current time and save it in a shared preference.

To get the time and date use:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());

To save this time in SharedPreference:

SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putString("NameOfThingToSave", currentDateandTime);
editor.commit();

Beware:

This technique largely depends on your system time, if a user changes the time/date on the device your logic will get messed up. The proper way to do this would be to sync the time with your server time!

Most importantly you should use your activities life-cycle methods to determine when the activity starts (OnCreate/onStart) ann when your activity stops (onStop)