我目前有一个Fragment,它有几个Buttons并包含一个onClickListener。每次单击其中一个按钮时,计数器变量将增加1,并使用SharedPreferences设置为另一个片段中TextView的文本。
即使应用程序完全关闭,计数器也会保持不变,并且会在应用程序的后续运行中显示。
我的新目标是在每天结束时将计数器重置为0(准确地说是23:59:00)。
我决定避免Google搜索来解决这个问题,并在Android Developer docs上找到了TimerTask,Calendar,Timer和Date API;我试图让这个与这些API一起使用。不幸的是,它没有像我计划的那样运作。变量 设置为0,但它们保持为零,并且只会增加到1,并在每次退出应用程序时返回0。
有没有更好的方法来解决这个问题?或者我的方法是否足够,我只需要调整/更改一些代码?
其中一个问题可能是我正在更改计数器变量引用(如果是,我应该在哪里更改它)?
以下是我的尝试:
FirstFragment
@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(将计数器设置为TextViews的文本):
@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);
答案 0 :(得分:3)
我个人会考虑使用AlarmManager和Calendar来设置时间。然后,您将启动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);
将MyService替换为实际的Service,当服务启动时,它可以: 1)将数字重置为0 2)检查应用程序是否正在运行,以查看是否需要立即更新文本框,或者是否可以等待用户启动应用程序 3)停止服务
在您遵循此代码之前需要调查的事项:
确保AlarmManager适合您,重启后重复闹钟不会运行(感谢Jawnnypoo澄清此事)请参阅下面的评论,其中链接到{{ 3}}以便BroadcastReceiver在重新启动后运行。
答案 1 :(得分:3)
也许只存储一年中的某一天并与当年的当天比较。
dayOfYear = DateFormat.format("D", new Date())
if (dayOfYear != lastResetDay) {
resetCounters();
}
答案 2 :(得分:2)
AlarmManager
注册一个警报,这会引发广播意图答案 3 :(得分:1)
使用AlarmManager完成此任务似乎是一项繁琐的工作。只需将另一个变量添加到SharedPreferences即可。存储上次更新计数器的时间。(可能是 - Calendar.getInstance()。getTimeInMillis())
因此,当您在获取计数器值时打开片段时,您必须最后一次更新它。根据当天检查存储的时间。如果它没有匹配,则重置计数器值。
如果我确实想念任何事情,请告诉我.. :)
答案 4 :(得分:-1)
有人建议:
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系统的时钟。