Code example for AlarmManager: Creating a periodic task

Methods: cancelsetRepeating

0
    public static void launchRepeatedCaching(Context ctx, boolean force) {
    	Intent i = new Intent(ctx, BackgroundCacheReciever.class);
    	PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, i, 0);
    	AlarmManager mgr = (AlarmManager) ctx.getSystemService(ALARM_SERVICE);
    	Log.d(TAG, "Cancelling the previous alarm...");
    	mgr.cancel(pi);
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
    	if(!sp.getBoolean("backgroundCacheEnabledPref", false) && !force) {
    		Log.d(TAG, "Caching disabled. Returning back...");
    		return; 
    	} 
    	int hour = Integer.parseInt(sp.getString("backgroundCacheStartTimePref", "6"));
    	int cacheFreq = Integer.parseInt(sp.getString("backgroundCacheFreqPref", "1"));
    	long interval = ONE_DAY / cacheFreq;
    	Calendar cal = Calendar.getInstance();
    	long now = System.currentTimeMillis();
    	cal.set(Calendar.HOUR_OF_DAY, hour);
    	cal.set(Calendar.MINUTE, 0);
    	cal.set(Calendar.SECOND, 0);
    	long sixAm = cal.getTimeInMillis();
    	long gap = now - sixAm;
    	if(gap < 0) {
    		cal.add(Calendar.DAY_OF_MONTH, -1);
    		sixAm = cal.getTimeInMillis();
    		gap = now - sixAm;
    	} 
    	long next = ((gap / interval) + 1) * interval;
    	next += sixAm;
    	long diff = next - now;
    	Log.d(TAG, "Alarm for interval="+interval+" firstTime="+next+" now="+now+" diff="+diff);
    	mgr.setRepeating(AlarmManager.RTC_WAKEUP, next, interval, pi);
    	return; 
    } 
 
    /** 
     * Checks when was the last time sync was performed 
Stop searching for code, let great code find you!  Add Codota to your java IDE