据说我有一个名为 floatValue 的共享首选项浮点值。当设备检测到新的一天时,如何将 floatValue 自动设置为 0?例如今天是 2017 年 2 月 1 日,floatValue 的值为 1250.23。是否可以将其重置为0,并且我的textView将显示0,这样当用户第二天早上醒来时,他会注意到textview的文本是0。
对于缩进,我深表歉意。基本上,我将 newTodayFloatValue 初始化为 0,因为我需要 TodayValueToBeAdded 附加到 newTodayFloatValue 中。然后我将此值保存到 SharedPreferences 中!但我希望这可以在 date_changed 之后重置。
float newTodayFloatValue = 0;
tvTodayFloatValue = (TextView)findViewById(R.id.todayfloatValueTextView);
Intent intent1 = getIntent();
float todayValueToBeAdded = intent1.getFloatExtra("strValueToBeAdded", 0.0f);
final SharedPreferences totalTodayfloatValue = getSharedPreferences("totalTodayfloatValue", 0);
newTodayFloatValue = totalTodayfloatValue.getFloat("totalTodayfloatValue", 0);
newTodayFloatValue = newTodayFloatValue + todayValueToBeAdded;
SharedPreferences.Editor editor = totalTodayfloatValue.edit();
editor.putFloat("totalTodayfloatValue", newTodayFloatValue);
editor.commit();
tvTodayFloatValue.setText(String.valueOf(newTodayFloatValue));
最佳答案
您可以通过操作使用广播接收器
"android.intent.action.DATE_CHANGED"
每当日期自动更改(因为日期实际上已更改)或由用户显式更改时,它将触发。
为了即使在您的应用未运行时也能收到此广播,您需要使用提到的 Intent 过滤器在 list 中声明它。
<receiver
android:name=".DateChangeReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED" />
</intent-filter>
</receiver>
然后在接收器中,您可以更改 SharedPreferences
public class DateChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("YOUR_INT", 0);
editor.apply();
}
}
关于java - 如何自动更新 SharedPreferences 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41975511/