I have created a periodic execution of runnable task by using handler in android, but I want to pass an argument in that periodic task execution, I have tried 2 approaches to pass an argument,
1 - By declaring a class in the method
void Foo(String str) {
class OneShotTask implements Runnable {
String str;
OneShotTask(String s) { str = s; }
public void run() {
someFunc(str);
}
}
Thread t = new Thread(new OneShotTask(str));
t.start();
}
2 - and by putting it in a function
String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);
private Runnable createRunnable(final String paramStr){
Runnable aRunnable = new Runnable(){
public void run(){
someFunc(paramStr);
}
};
return aRunnable;
}
Reference for these above 2 approach can be found on Runnable with a parameter?
below is my code in which I have used the 1 approach, but either I use 1 or 2 approach there are two problems that remains by passing an argument in a periodic runnable task,
1 problem - the counter variable inside my class is overwritten every time the code repeats itself. If I define this counter variable outside of class and method as a global variable instead of a local variable then it works fine, but that is not my requirement.
2 problem - assume 1 problem is solved by using the counter variable as a global variable then the counter increments after the first execution and with the second execution it unregistered the sensor i.e. mSensorListener but it is unable to remove the further Callbacks with this command,
// Removes pending code execution
staticDetectionHandler.removeCallbacks(staticDetectionRunnableCode(null));
this above command is also not working with the onPause method, it still periodically execute after this command execution ? I don't able to understand what is happening, can anyone provide a solution for this ? below is my code,
Runnable staticDetectionRunnableCode(String str){
class staticDetectionRunnableClass implements Runnable{
String str;
private int counter = 0;
staticDetectionRunnableClass(String str){
this.str = str;
}
@Override
public void run() {
// Do something here
Log.e("", "staticDetectinoHandler Called");
Debug.out(str + " and value of " + counter);
// Repeat this runnable code block again every 5 sec, hence periodic execution...
staticDetectionHandler.postDelayed(staticDetectionRunnableCode(str), constants.delay_in_msec * 5); // for 5 second
if(counter >= 1){
// Removes pending code execution
staticDetectionHandler.removeCallbacks(staticDetectionRunnableCode(null));
// unregister listener
mSensorManager.unregisterListener(mSensorListener);
}
counter++;
}
}
Thread t = new Thread(new staticDetectionRunnableClass(str));
return t;
}