/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.tv.util; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Handler; import android.support.annotation.WorkerThread; import android.util.Log; import java.util.Date; /** * Repeatedly executes a {@link Runnable}. * *
The next execution time is saved to a {@link SharedPreferences}, and used on the next start.
* The given {@link Runnable} will run in the main thread.
*/
public final class RecurringRunner {
private static final String TAG = "RecurringRunner";
private static final boolean DEBUG = false;
private final Handler mHandler;
private final long mIntervalMs;
private final Runnable mRunnable;
private final Context mContext;
private final String mName;
private boolean mRunning;
public RecurringRunner(Context context, long intervalMs, Runnable runnable) {
mContext = context.getApplicationContext();
mRunnable = runnable;
mIntervalMs = intervalMs;
if (DEBUG) Log.i(TAG, "Delaying " + (intervalMs / 1000.0) + " seconds");
mName = runnable.getClass().getCanonicalName();
mHandler = new Handler(mContext.getMainLooper());
}
public void start() {
if (mRunning) {
Utils.engThrowElseWarn(TAG, "start is called twice.", new IllegalStateException());
return;
}
mRunning = true;
new AsyncTask