Timer act only if i touch the display (OnTouchListener)
-
27-09-2019 - |
Question
The Timer works fine. The problem is that the method _dw.newgame() just get executed(if two seconds are over) if i touch the display. Maybe it have sth to do with the "OnTouchListener" ?
public class DrawView extends View implements OnTouchListener{
Timer timer = new Timer();
public DrawView(Context context)
{
timer.schedule(new Task(this),0, 2000);
}
public boolean onTouch(View view, MotionEvent event)
{}
}
class Task extends TimerTask
{
private DrawView _dw;
public Task(DrawView dw){ this._dw = dw;}
public void run()
{ _dw.newgame(); }
}
Solution
Maybe you should start the timer in the onCreate
method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(Bundle savedInstanceState);
timer = new Timer();
timer.schedule(new Task(this), 0, 2000);
}
second try with handler:
public class DrawView extends View implements OnTouchListener{
private Timer timer = new Timer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(Bundle savedInstanceState);
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
handler.sendEmptyMessage();
}
}, 0, 2000);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
newgame();
}
};
}
I did not compile this but it should work like this.
I noticed another thing: I suppose newgame() should only be called once.
timer.schedule(new Task(this), 0, 2000);does that every 2 secs.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow