multithreading - Passing an Argument in a periodic runnable task execution using handler in Android -
i have created periodic execution of runnable task using handler in android, want pass argument in periodic task execution, have tried 2 approaches pass argument,
1 - declaring class in 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 - , putting in 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 these above 2 approach can found on runnable parameter?
below code in have used 1 approach, either use 1 or 2 approach there 2 problems remains passing argument in periodic runnable task,
1 problem - counter variable inside class overwritten every time code repeats itself. if define counter variable outside of class , method global variable instead of local variable works fine, not requirement.
2 problem - assume 1 problem solved using counter variable global variable counter increments after first execution , second execution unregistered sensor i.e. msensorlistener unable remove further callbacks command,
// removes pending code execution staticdetectionhandler.removecallbacks(staticdetectionrunnablecode(null));
this above command not working onpause method, still periodically execute after command execution ? don't able understand happening, can provide solution ? below 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() { // here log.e("", "staticdetectinohandler called"); debug.out(str + " , value of " + counter); // repeat runnable code block again every 5 sec, hence periodic execution... staticdetectionhandler.postdelayed(staticdetectionrunnablecode(str), constants.delay_in_msec * 5); // 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; }
Comments
Post a Comment