As far as I know, there is no system API for me to get user idle time. When I say user idle time, I mean user have some interaction on the touch screen with
Instead writing it down every time, from everywhere, make this a global function in your App:
public class MyApp extends Application {
private static SharedPreferences sPreference;
private static final long MIN_SAVE_TIME = 1000;
private static final String PREF_KEY_LAST_ACTIVE = "last_active";
private static final String PREF_ID_TIME_TRACK = "time_track";
public static void saveTimeStamp(){
if(getElapsedTime() > MIN_SAVE_TIME){
sPreference.edit().putLong(PREF_KEY_LAST_ACTIVE, timeNow()).commit();
}
}
public static long getElapsedTime(){
return timeNow() - sPreference.getLong(PREF_KEY_LAST_ACTIVE,0);
}
private static long timeNow(){
return Calendar.getInstance().getTimeInMillis();
}
@Override
public void onCreate() {
super.onCreate();
sPreference = getSharedPreferences(PREF_ID_TIME_TRACK,MODE_PRIVATE);
}
}
Add Application class to manifest: <application android:name="com.example.MyApp"
Place saving functionality in an abstract Activity class:
public abstract class TimedActivity extends Activity {
@Override
public void onUserInteraction() {
super.onUserInteraction();
MyApp.saveTimeStamp();
}
public long getElapsed(){
return MyApp.getElapsedTime();
}
}
Now, extend all your activities from this class, all of them will be auto-save time, and will be able to use getElapsed()
.