アンドロイドにいくつかの日付を保存してSharedPreferences
取得する必要があります。を使用してリマインダー アプリを作成AlarmManager
していますが、将来の日付のリストを保存する必要があります。ミリ秒単位で取得できる必要があります。まず、今日の現在時刻と未来の時刻の間の時間を計算し、共有設定に格納することを考えました。しかし、私はそれを使用する必要があるため、その方法は機能していませんAlarmManager
。
45208 次
3 に答える
167
long
正確な日付を保存して読み込むには、オブジェクトの (数値) 表現を使用できDate
ます。
例:
//getting the current time in milliseconds, and creating a Date object from it:
Date date = new Date(System.currentTimeMillis()); //or simply new Date();
//converting it back to a milliseconds representation:
long millis = date.getTime();
これを使用して、次のようにデータを保存または取得できDate
ますTime
SharedPreferences
保存:
SharedPreferences prefs = ...;
prefs.edit().putLong("time", date.getTime()).apply();
読み返してください:
Date myDate = new Date(prefs.getLong("time", 0));
編集
追加を保存したい場合はTimeZone
、その目的のために次のようなヘルパーメソッドを書くことができます(私はそれらをテストしていません。何か問題がある場合は自由に修正してください):
public static Date getDate(final SharedPreferences prefs, final String key, final Date defValue) {
if (!prefs.contains(key + "_value") || !prefs.contains(key + "_zone")) {
return defValue;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(prefs.getLong(key + "_value", 0));
calendar.setTimeZone(TimeZone.getTimeZone(prefs.getString(key + "_zone", TimeZone.getDefault().getID())));
return calendar.getTime();
}
public static void putDate(final SharedPreferences prefs, final String key, final Date date, final TimeZone zone) {
prefs.edit().putLong(key + "_value", date.getTime()).apply();
prefs.edit().putString(key + "_zone", zone.getID()).apply();
}
于 2012-09-09T21:58:05.217 に答える
3
于 2018-10-05T20:40:11.217 に答える