我希望实现一种条纹功能,显示用户打开应用程序的次数。我希望柜台每天增加一个。如果用户应该跳过一天,请将计数器保存为一种“高分”并重新启动计数器
到目前为止,我已经能够使用以下代码计算应用程序打开的次数:
if (savedInstanceState == null) {
//initialize streak counter
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
streakCount = prefs.getInt("counter", 0);
streakCount++;
editor.putInt("counter", streakCount);
editor.apply();
Toast.makeText(this, "App Opened Count is: " + streakCount, Toast.LENGTH_SHORT)
.show();
}
任何关于如何实现这一点的想法都将受到赞赏。
答案 0 :(得分:1)
只需将其用作示例
SharedPreferences sharedPreferences = getSharedPreferences("YOUR PREF KEY", Context.MODE_PRIVATE);
Calendar c = Calendar.getInstance();
int thisDay = c.get(Calendar.DAY_OF_YEAR); // GET THE CURRENT DAY OF THE YEAR
int lastDay = sharedPreferences.getInt("YOUR DATE PREF KEY", 0); //If we don't have a saved value, use 0.
int counterOfConsecutiveDays = sharedPreferences.getInt("YOUR COUNTER PREF KEY", 0); //If we don't have a saved value, use 0.
if(lastDay == thisDay -1){
// CONSECUTIVE DAYS
counterOfConsecutiveDays = counterOfConsecutiveDays + 1;
sharedPreferences.edit.putInt("YOUR DATE PREF KEY", thisDay);
sharedPreferences.edit.putInt("YOUR COUNTER PREF KEY", counterOfConsecutiveDays).commit;
} else {
sharedPreferences.edit.putInt("YOUR DATE PREF KEY", thisDay);
sharedPreferences.edit.putInt("YOUR COUNTER PREF KEY", 1).commit();
}