如何在某个时间从 Activity 运行 AsyncTask?
我的活动中有一个异步任务,我只想每周运行一次。我该怎么做呢?
我正在检索大约 7 个 URL 的列表,然后将它们放入 SharedPreference 中。
我只想每周更新一次并检查我的活动中的新网址。这将在我的主要活动中。
I have an AsyncTask in a activity that i only want to run once a week. How do i go about doing this?
I am retrieving a list of URL's about 7 of them and then putting them in SharedPreference.
i only want to update and check for new URL's once a week from my activity. This will be in my Main Activity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在共享首选项中使用异步任务时保存日期。
因此,每当主活动开始时,您都可以检查当前日期和共享首选项中的日期,如果超过 7 天,您可以再次执行异步任务并将保存的日期更新为当前日期。
我相信您已经知道如何将字符串放入共享首选项中并访问它们。
这只是要做的事情的基本代码。您需要对其进行一些修改才能使其为您工作。
如果你把它放在 onCreate 中,
上面的代码只是检索当前日期、7 天后的日期,并且还找到 2 个日期之间的天数差异。您需要获取保存的日期并找到 7 天后的日期,并检查当前日期之间的差异是否 >= 到 7。如果为真,则执行异步任务。
这是简单的方法。
正如 JoeLallouz 提到的,只有当用户参加该活动时,这才有效。但由于 >= 检查,即使他在一个月后打开它也会起作用。但是,如果即使用户没有打开您的应用程序,您也需要执行此操作,则需要查看 AlarmManager 类。
You could save the date when you use the asynctask in the shared preferences.
So whenever the Main Activity starts you can check the current date and the date in the shared preferences, if its more than 7 days, you can do your asynctask again and update the saved date to the current date.
I believe you already know how to put strings inside shared preferences and to access them.
This is just the basic code of what to do. You will need to modify it a bit to get it working for you.
If you put this in the onCreate
The above code just retrieves the current date, the date after 7 days, and also find the difference in days between the 2 dates. You will need to get the saved date and find the after 7 days date and check if the differnce between the current date is >= to 7. If its true, do your async task.
This is the simple way to do it.
As JoeLallouz mentioned this will only work if user goes to that activity. But it will work even if he opens after a month due to the >= checking. But if you need to do it even if the user doesn't open you're app, you will need to look into the AlarmManager class.