Issue
I'm developping an android app which uses an api. The app calls the api and stores the information. But when the app is paused and resumed after a long period, the informations may no more be valid at that time. How can I check the period of time that the app was paused so as to refresh the informations. Some thing like "refresh if the app is paused for an hour and is then resumed".
Solution
Although, You should use onResume()
to change whatever you want to check when app resumes after being paused for any amount of time.
Now, If you really want to check how much time it was actually paused for, I'd prefer a simple logic like this:
Save the current time in
SharedPreferences
when the data is loaded asDate date = new Date(System.currentTimeMillis()); //or simply new Date(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.edit().putLong("Time", date.getTime()).apply();
In
onResume()
, calculate the difference between current time and saved time as@Override public void onResume(){ super.onResume(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); Date savedDate = new Date(prefs.getLong("Time", 0)); //0 is the default value Date currentDate = new Date(System.currentTimeMillis()); long diff = currentDate.getTime() - savedDate.getTime(); //This difference is in milliseconds. long diffInHours = TimeUnit.MILLISECONDS.toHours(diff); //To convert it in hours // You can also use toMinutes() for calculating it in minutes //Now, simple check if the difference is more than your threshold, perform your function as if(diffInHours > 1){ //do something } }
You can also use a Global variable instead of SharedPreferences
to save the time when data loads but that can be risky as it may get cleared by the system.
Edit: Also, if you want to check the difference between Pause and Resume only and not between data loads and Resume then do the first step in onPause()
.
Answered By - Lalit Fauzdar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.