在一天中的特定时间重置整数值
Reset Value of an Integer at A Specific Time of Day
我目前有一个具有多个按钮并包含一个 onClickListener 的片段。每次单击其中一个按钮时,计数器变量都会递增 1,并使用 SharedPreferences 将其设置为另一个 Fragment 中 TextView 的文本。
即使在应用程序完全关闭后,计数器也会保持不变,并会出现在应用程序的后续运行中。
我的新目标是在每天结束时将计数器重置回 0(确切地说,时间是 23:59:00)。
我决定避免 Google 搜索来解决这个问题,并在 Android 开发人员文档中找到了 TimerTask、Calendar、Timer 和 Date API;我试图让它与那些 API 一起工作。不幸的是,它没有按照我的计划进行。变量 被 设置回 0,但它们保持为零并且只会增加到 1,并且每次我退出应用程序时都会回到 0。
有没有更好的方法来解决这个问题?还是我的方法足够了,我只需要adjust/change一些代码?
其中一个问题可能是我也在更改计数器变量引用的地方(如果是这样,我应该在哪里更改它)?
这是我的尝试:
第一个片段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating the layout
View v = inflater.inflate(R.layout.starting_fragment, container, false);
//Instantiate new Timer
Timer timer = new Timer();
// Creates a Calendar object that specifies a specific time of day
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 20);
cal.set(Calendar.MINUTE, 57);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.MILLISECOND, 00);
// Instantiate a day object and use the time of day from cal object as its data
Date date = cal.getTime();
TimerTask tt = new TimerTask() {
// Sets the counter variables back to 0
@Override
public void run() {
COUNT_OOL = 0;
COUNT_WTE = 0;
COUNT_BLO = 0;
COUNT_BLK = 0;
COUNT_HBL = 0;
COUNT_GRN = 0;
COUNT_MTE = 0;
}
};
// Resets the counter variables (to 0) at the time specified by the date object
timer.schedule(tt, date);
// Stores count for each button back into their respective count variable
// Initializes the value from previous runs of app to subsequent runs of app
// This way, count variables will never get set back to 0 after onDestroy()
COUNT_OOL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("oolongCount", 0);
COUNT_WTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("whiteCount", 0);
COUNT_BLO = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("bloomingCount", 0);
COUNT_BLK = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("blackCount", 0);
COUNT_HBL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("herbalCount", 0);
COUNT_GRN = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("greenCount", 0);
COUNT_MTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("mateCount", 0);
增加计数器变量的 onClick 方法:
@Override
public void onClick(View view) {
int id = view.getId();
/*
* Use the View interface with OnClickListener to get the Button ID's
* Then you can run a switch on the Buttons (because normally switches
* cannot be run on buttons
*/
if (id == R.id.tea_type1) {
Builder oolongBuilder = new AlertDialog.Builder(StartingFragment.this.getActivity(),
AlertDialog.THEME_HOLO_LIGHT);
oolongBuilder.setPositiveButton("Hot",
//Starts OolongTeaActivity for hot tea when clicked
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(StartingFragment.this.getActivity(),
OolongTeaActivity.class);
StartingFragment.this.getActivity().startActivity(i);
}
});
oolongBuilder.setNeutralButton("Iced",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(StartingFragment.this.getActivity(),
ColdOolongTeaActivity.class);
StartingFragment.this.getActivity().startActivity(i);
}
});
oolongBuilder.setTitle("Oolong Tea");
oolongBuilder.setMessage("How Do You Like Your Tea?");
AlertDialog oolongDialog = oolongBuilder.create();
oolongDialog.show();
COUNT_OOL++;
SharedPreferences pref1 = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = pref1.edit();
editor1.putInt("oolongCount", COUNT_OOL);
editor1.commit();
}
SecondFragment(将计数器设置为 TextView 的文本):
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tea_counter, container, false);
oolongCounterText = (TextView) rootView.findViewById(R.id.oolong_counter_tv);
SharedPreferences pref1 = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
Integer counter1 = pref1.getInt("oolongCount", 0);
String s1 = String.valueOf(counter1);
oolongCounterText.setText(s1);
一些建议:
1.
COUNT_OOL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("oolongCount", 0);
COUNT_WTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("whiteCount", 0);
COUNT_BLO = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("bloomingCount", 0);
COUNT_BLK = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("blackCount", 0);
COUNT_HBL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("herbalCount", 0);
COUNT_GRN = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("greenCount", 0);
COUNT_MTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("mateCount", 0);
应该这样编辑
private SharedPreferences sharedPreferences;
sharedPreferences = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
COUNT_OOL = sharedPreferences.getInt("oolongCount", 0);
等等
根据规范需要命名
我觉得你的代码问题是写的比较乱,整理完先看看吧,你先看看,我现在写一下,顺便说一句。也许你应该使用 android 系统时钟。
我个人会考虑使用 AlarmManager with the Calendar to set the time. You will then fire off a Service 来完成您需要做的一切。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0,
new Intent(context, MyService.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
用实际的 Service 替换 MyService,当服务启动时它可以:
1)将数字重置为0
2) 检查应用程序是否 运行 查看是否需要立即更新文本框,或者是否可以等待用户启动应用程序
3) 停止服务
在遵循此代码之前需要调查的事项:
确保 AlarmManager is right for you, a repeating alarm will NOT run after a reboot (Thanks to Jawnnypoo for clarifying this) Please see his comment below in which he links to a BroadcastReceiver so that the AlarmManager 将在重启后 运行。
- 只保存最后一次重置计数器的时间。
- 片段第一次开始时:
- 它会检查上次重置计数器的时间,并且可能会重置它们
- 它通过
AlarmManager
为下一个午夜注册一个警报,这会引发广播意图
- 它注册一个广播接收器。
- 当广播接收器接收到意图时,它会重置计数器,通知片段并注册下一个午夜的闹钟。
- 如果 activity 已停止,请移除您的广播接收器并取消闹钟,这样该应用程序就不会执行本来不可见的工作。
为此任务使用 AlarmManager 似乎是一项乏味的工作。只需将另一个变量添加到您的 SharedPreferences。存储上次更新计数器的时间。(可能 - Calendar.getInstance().getTimeInMillis())
所以当你在获取计数器值的同时打开片段时,你必须获取它上次更新的时间。检查您当前日期的存储时间。如果不匹配,则重置计数器值。
如果我遗漏了什么请告诉我..:)
也许只存储一年中的第几天并与一年中的当前日期进行比较。
dayOfYear = DateFormat.format("D", new Date())
if (dayOfYear != lastResetDay) {
resetCounters();
}
我目前有一个具有多个按钮并包含一个 onClickListener 的片段。每次单击其中一个按钮时,计数器变量都会递增 1,并使用 SharedPreferences 将其设置为另一个 Fragment 中 TextView 的文本。
即使在应用程序完全关闭后,计数器也会保持不变,并会出现在应用程序的后续运行中。
我的新目标是在每天结束时将计数器重置回 0(确切地说,时间是 23:59:00)。
我决定避免 Google 搜索来解决这个问题,并在 Android 开发人员文档中找到了 TimerTask、Calendar、Timer 和 Date API;我试图让它与那些 API 一起工作。不幸的是,它没有按照我的计划进行。变量 被 设置回 0,但它们保持为零并且只会增加到 1,并且每次我退出应用程序时都会回到 0。
有没有更好的方法来解决这个问题?还是我的方法足够了,我只需要adjust/change一些代码?
其中一个问题可能是我也在更改计数器变量引用的地方(如果是这样,我应该在哪里更改它)?
这是我的尝试:
第一个片段
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating the layout
View v = inflater.inflate(R.layout.starting_fragment, container, false);
//Instantiate new Timer
Timer timer = new Timer();
// Creates a Calendar object that specifies a specific time of day
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 20);
cal.set(Calendar.MINUTE, 57);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.MILLISECOND, 00);
// Instantiate a day object and use the time of day from cal object as its data
Date date = cal.getTime();
TimerTask tt = new TimerTask() {
// Sets the counter variables back to 0
@Override
public void run() {
COUNT_OOL = 0;
COUNT_WTE = 0;
COUNT_BLO = 0;
COUNT_BLK = 0;
COUNT_HBL = 0;
COUNT_GRN = 0;
COUNT_MTE = 0;
}
};
// Resets the counter variables (to 0) at the time specified by the date object
timer.schedule(tt, date);
// Stores count for each button back into their respective count variable
// Initializes the value from previous runs of app to subsequent runs of app
// This way, count variables will never get set back to 0 after onDestroy()
COUNT_OOL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("oolongCount", 0);
COUNT_WTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("whiteCount", 0);
COUNT_BLO = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("bloomingCount", 0);
COUNT_BLK = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("blackCount", 0);
COUNT_HBL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("herbalCount", 0);
COUNT_GRN = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("greenCount", 0);
COUNT_MTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("mateCount", 0);
增加计数器变量的 onClick 方法:
@Override
public void onClick(View view) {
int id = view.getId();
/*
* Use the View interface with OnClickListener to get the Button ID's
* Then you can run a switch on the Buttons (because normally switches
* cannot be run on buttons
*/
if (id == R.id.tea_type1) {
Builder oolongBuilder = new AlertDialog.Builder(StartingFragment.this.getActivity(),
AlertDialog.THEME_HOLO_LIGHT);
oolongBuilder.setPositiveButton("Hot",
//Starts OolongTeaActivity for hot tea when clicked
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(StartingFragment.this.getActivity(),
OolongTeaActivity.class);
StartingFragment.this.getActivity().startActivity(i);
}
});
oolongBuilder.setNeutralButton("Iced",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(StartingFragment.this.getActivity(),
ColdOolongTeaActivity.class);
StartingFragment.this.getActivity().startActivity(i);
}
});
oolongBuilder.setTitle("Oolong Tea");
oolongBuilder.setMessage("How Do You Like Your Tea?");
AlertDialog oolongDialog = oolongBuilder.create();
oolongDialog.show();
COUNT_OOL++;
SharedPreferences pref1 = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = pref1.edit();
editor1.putInt("oolongCount", COUNT_OOL);
editor1.commit();
}
SecondFragment(将计数器设置为 TextView 的文本):
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tea_counter, container, false);
oolongCounterText = (TextView) rootView.findViewById(R.id.oolong_counter_tv);
SharedPreferences pref1 = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
Integer counter1 = pref1.getInt("oolongCount", 0);
String s1 = String.valueOf(counter1);
oolongCounterText.setText(s1);
一些建议:
1.
COUNT_OOL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("oolongCount", 0);
COUNT_WTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("whiteCount", 0);
COUNT_BLO = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("bloomingCount", 0);
COUNT_BLK = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("blackCount", 0);
COUNT_HBL = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("herbalCount", 0);
COUNT_GRN = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("greenCount", 0);
COUNT_MTE = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE).getInt("mateCount", 0);
应该这样编辑
private SharedPreferences sharedPreferences;
sharedPreferences = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
COUNT_OOL = sharedPreferences.getInt("oolongCount", 0);
等等
根据规范需要命名
我觉得你的代码问题是写的比较乱,整理完先看看吧,你先看看,我现在写一下,顺便说一句。也许你应该使用 android 系统时钟。
我个人会考虑使用 AlarmManager with the Calendar to set the time. You will then fire off a Service 来完成您需要做的一切。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0,
new Intent(context, MyService.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
用实际的 Service 替换 MyService,当服务启动时它可以: 1)将数字重置为0 2) 检查应用程序是否 运行 查看是否需要立即更新文本框,或者是否可以等待用户启动应用程序 3) 停止服务
在遵循此代码之前需要调查的事项:
确保 AlarmManager is right for you, a repeating alarm will NOT run after a reboot (Thanks to Jawnnypoo for clarifying this) Please see his comment below in which he links to a BroadcastReceiver so that the AlarmManager 将在重启后 运行。
- 只保存最后一次重置计数器的时间。
- 片段第一次开始时:
- 它会检查上次重置计数器的时间,并且可能会重置它们
- 它通过
AlarmManager
为下一个午夜注册一个警报,这会引发广播意图 - 它注册一个广播接收器。
- 当广播接收器接收到意图时,它会重置计数器,通知片段并注册下一个午夜的闹钟。
- 如果 activity 已停止,请移除您的广播接收器并取消闹钟,这样该应用程序就不会执行本来不可见的工作。
为此任务使用 AlarmManager 似乎是一项乏味的工作。只需将另一个变量添加到您的 SharedPreferences。存储上次更新计数器的时间。(可能 - Calendar.getInstance().getTimeInMillis())
所以当你在获取计数器值的同时打开片段时,你必须获取它上次更新的时间。检查您当前日期的存储时间。如果不匹配,则重置计数器值。
如果我遗漏了什么请告诉我..:)
也许只存储一年中的第几天并与一年中的当前日期进行比较。
dayOfYear = DateFormat.format("D", new Date())
if (dayOfYear != lastResetDay) {
resetCounters();
}