而不是每次都从任何地方写下来,让它成为你应用程序中的一个全局函数:
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);
}
}
将应用程序类添加到清单:<application android:name="com.example.MyApp"
将保存功能放在抽象的 Activity 类中:
public abstract class TimedActivity extends Activity {
@Override
public void onUserInteraction() {
super.onUserInteraction();
MyApp.saveTimeStamp();
}
public long getElapsed(){
return MyApp.getElapsedTime();
}
}
现在,从这个类扩展你所有的活动,它们都将自动保存时间,并且可以使用getElapsed()
.