Tracking user idle time within the app in Android

南笙酒味 提交于 2019-12-01 11:58:18

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!