Skip to content Skip to sidebar Skip to footer

Tracking User Idle Time Within The App In Android

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 within my app. Therefore, I

Solution 1:

Instead writing it down every time, from everywhere, make this a global function in your App:

publicclassMyAppextendsApplication {
    privatestatic SharedPreferences sPreference;

    privatestaticfinallongMIN_SAVE_TIME=1000;
    privatestaticfinalStringPREF_KEY_LAST_ACTIVE="last_active";
    privatestaticfinalStringPREF_ID_TIME_TRACK="time_track";

    publicstaticvoidsaveTimeStamp(){
        if(getElapsedTime() > MIN_SAVE_TIME){
            sPreference.edit().putLong(PREF_KEY_LAST_ACTIVE, timeNow()).commit();
        }
    }

    publicstaticlonggetElapsedTime(){
        return timeNow() - sPreference.getLong(PREF_KEY_LAST_ACTIVE,0);
    }

    privatestaticlongtimeNow(){
        return Calendar.getInstance().getTimeInMillis();
    }

    @OverridepublicvoidonCreate() {
        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:

publicabstractclassTimedActivityextendsActivity {

    @OverridepublicvoidonUserInteraction() {
        super.onUserInteraction();
        MyApp.saveTimeStamp();
    }

    publiclonggetElapsed(){
        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().

Post a Comment for "Tracking User Idle Time Within The App In Android"