android - 如何每天为android中的片段运行一次代码?
问题描述
我找到了这个视频(https://www.youtube.com/watch?v=MZjIhaMKnlo)并复制(几乎)确切的代码来每天一次为用户分配一些任务,如下所示:
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
int lastDay = settings.getInt("day",0);
if (lastDay != currentDay) {
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day", currentDay);
editor.commit();
str1 = "oic_" + random.nextInt(76);
int id1 = getResources().getIdentifier("com.codepath.wmgf8:drawable/" + str1, null, null);
daily_goal1.setBackgroundResource(id1);
}
唯一的区别是我把this.getActivity().getSharedPreferences
而不是getSharedPreferences
因为我使用的是Fragment
.
但是,每次我打开应用程序时它都会分配随机图像。
有人可以帮我解决这个问题吗?
编辑
我发现活动无法在 Fragment 中传递...
似乎唯一的方法是完全创建一个新活动。
不过,如果还有其他选择,请告诉我!
解决方案
我解决了如下问题:
Calendar calendar = Calendar.getInstance();
int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
int currentWeek = calendar.get(Calendar.WEEK_OF_MONTH);
SharedPreferences settings = getSharedPreferences("PREFS", 0);
int lastDay = settings.getInt("day",0);
int lastWeek = settings.getInt("week", 0);
if (lastDay != currentDay) {
SharedPreferences.Editor editor = settings.edit();
editor.putInt("day", currentDay);
//random
Random random = new Random();
//item of the day
String str0 = IOD();
//commit to system
editor.putString("IOD", str0);
//daily_goals
String[] str = new String[8];
str = daily_goal();
editor.putString("daily_goal1", str[0]);
editor.putString("daily_goal2", str[1]);
editor.putString("daily_goal3", str[2]);
editor.putString("daily_goal4", str[3]);
editor.putString("daily_goal1_text", str[4]);
editor.putString("daily_goal2_text", str[5]);
editor.putString("daily_goal3_text", str[6]);
editor.putString("daily_goal4_text", str[7]);
//commit
editor.commit();
}
推荐阅读
- go - 提供 http 服务的打开文件过多
- java - Spring Boot 2.xx 与 hibernate 4.3.x 的兼容性问题
- ionic-framework - 带有 Web 组件图像的图像网格布局
- android - 如何解决 recyclerView Android 中的 addInArray 异常和 removeFromArray 异常?
- php - get_permalink(0) 的结果;
- java - 如何在另一个/下一个活动中将微调器选择的值显示为 android 中的微调器本身?
- vue.js - Vuetify v-data-table 不更新分页
- mongodb - 如何处理`MongoException`?
- regex - 从 VS Code 中的正则表达式替换特定字符
- reactjs - 如何在自定义 api 处理程序反应 javascript 类中访问 redux 存储