Skip to content

Instantly share code, notes, and snippets.

@c3ph3us
Created June 22, 2016 12:33
Show Gist options
  • Save c3ph3us/7d237d540e60597369856cb1fa652a23 to your computer and use it in GitHub Desktop.
Save c3ph3us/7d237d540e60597369856cb1fa652a23 to your computer and use it in GitHub Desktop.
an example of use runnable loop via handler post delayed
/*
* Copyright © 2015-2016. by ceph3us
* All Rights Reserved.
* www.ceph3us.pl
*/
package pl.ceph3us.android.examples;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
/**
* Created by ceph3us on 22.06.16.
*/
public class HandlerLoopOnActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** create a handler - needs to be final to use it in anonymous class/method */
final Handler handler = new Handler();
/** post to this handler an anonymous class implementing runnable interface */
handler.post(new Runnable() {
/** /////// body of anonymous class //////////// */
/** counter */
int counter = 0;
/** initial delay time in ms */
int delay = 5000;
/** run method of runnable interface */
@Override
public void run() {
/** pre method */
doPreMethod();
boolean wasPlacedInQue = false;
/** check if our counter was reached */
if (counter <= 10) {
/** try place this anonymous class in messed que with delayed execution of {@var time} seconds */
wasPlacedInQue = handler.postDelayed(this, delay);
} else {
/** check if we satisfied some conditions to break execution */
boolean handled = doCounterReachedMethod();
/** if so return and don't execute rest of the code in this method */
if (handled) return;
/** else go with forward execution */
}
/** check if runnable was places successful in que */
if (wasPlacedInQue) {
/** if was do on placed successful method */
doOnPlacedSucceedMethod();
/** else execute on failure method */
} else doOnPlacedFailureMethod();
}
private boolean doCounterReachedMethod() {
/**
* example check if execution satisfies us
* so we can abandon rest of code execution after this method exits
* by check if current time in ms is even or odd
* */
return (System.currentTimeMillis() % 2) == 0;
}
private void doOnPlacedFailureMethod() {
/** for example log failure of post execution */
Log.i("handler", "failure on count" + String.valueOf(counter));
/** increase counter */
counter++;
}
private void doOnPlacedSucceedMethod() {
/** increases the next execution delay by doubling it */
delay = delay * 2;
}
private void doPreMethod() {
/** for example log successful start of run() execution */
Log.i("handler", "runnable was placed successful - count: " + String.valueOf(counter));
}
}
/** /////// end of body of anonymous class //////////// */
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment