Reputation: 469
I'm trying to have a method execute every second by using an additional class that extends TimerTask
. I think the reason that it doesn't work is that I'm trying to execute a method that eventually returns a value back to the MainActivity. This is why: I tested the code by making the method not return anything (just print something to the console) and it worked.
Here's a summary of what my code looks like with the returning method:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timer timer = new Timer();
timer.schedule(new doStuff(), 0, 1000);
}
public void method1(String string){
//things happen
}
}
//----------------------------------------
class doStuff extends TimerTask{
@Override
public void run(){
String string = stringMethod();
MainActivity ma = new MainActivity();
ma.method1(string);
}
public String stringMethod(){
//gets the required string
return "String";
}
}
Note that the method itself doesn't return a value directly to MainActivity
. run()
does that.
When I try to run the code on my Android Device, LogCat says something about notify()
not blocking something. Not sure. Can't remember.
I just want to know if there's an easier way that doesn't require two classes before I tackle this.
*Sorry about the stupid names. I just made them for demo purposes.
Upvotes: 0
Views: 228
Reputation: 1111
Try using a handler:
final Handler handler=new Handler();
final Runnable runnable = new Runnable()
{
public void run()
{
//This will run every 1000ms. Put code here(UI safe)
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
Upvotes: 1