开发者

How to Run AsyncTask at a certain time from a Activity?

开发者 https://www.devze.com 2023-04-10 07:44 出处:网络
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 SharedP

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.


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.

private static String getToday(){
    Calendar objCalendar = new GregorianCalendar(Calendar.getInstance().getTimeZone());
    DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
    return objFormatter.format(objCalendar.getTime());
}

private static String getAfter7DaysDate(){
    Calendar objCalendar = new GregorianCalendar(Calendar.getInstance().getTimeZone());
    DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
    objCalendar.add(Calendar.DATE, 7);
    return objFormatter.format(objCalendar.getTime());
}

public int daysBetween(Date d1, Date d2){
     return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}

If you put this in the onCreate

    String today = getToday();
    String afterSevenDate = getAfter7DaysDate();

    DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
    try {
        Log.e(today,Integer.toString(daysBetween(objFormatter.parse(today),
                objFormatter.parse(afterSevenDate))));
    } catch (ParseException e) {
        e.printStackTrace();
    }

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号