Skip to content

Instantly share code, notes, and snippets.

@money4honey
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save money4honey/87da5b68e741a26abf75 to your computer and use it in GitHub Desktop.
Save money4honey/87da5b68e741a26abf75 to your computer and use it in GitHub Desktop.
This is Asynchronous Timer class for call periodic action
package ru.moneyhoney.playground;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
/* This is Asynchronous Timer class for call periodic action */
public class AsyncTimer extends AsyncTask<Void, Integer, Void> {
private static int mCounter = 0;
private static int mPeriod;
private Context mContext;
public AsyncTimer(Context context, int period) {
super();
mContext = context;
mPeriod = period;
}
@Override
protected Void doInBackground(Void... params) {
while (mCounter < mPeriod){
mCounter++;
publishProgress(mCounter);
if (isCancelled()) return null;
SystemClock.sleep(1000);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (mCounter == mPeriod){
mCounter = 0;
// periodic action below
// do something
}
}
public static void resetTimer(){
mCounter = 0;
}
public static void setPeriod(int period) {
mPeriod = period;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment