首页 > 解决方案 > 如何每天为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 中传递...

似乎唯一的方法是完全创建一个新活动。

不过,如果还有其他选择,请告诉我!

标签: androidandroid-studioandroid-fragmentscalendarsharedpreferences

解决方案


我解决了如下问题:


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();
        }

推荐阅读