正确的方法是匿名inheritanceTimerTask,在run方法中保持对’this’的引用
我用一个匿名的“具体”类TimerTask
,这样:
public void setTimedTask() { /* Note: 'this' implements an interface called UpdateIndicatorsReceiver */ final UpdateIndicatorsReceiver receiver = this; final TimerTask timerTask = new TimerTask() { @Override public void run() { /* The interface UpdateIndicatorsReceiver has an updateIndicators method */ receiver.updateIndicators(); } }; /* Code to actually set the timer.... */ }
请注意声明一个名为receiver
的本地final
字段并将其设置this
的奇怪之处。 为了在匿名类的run
方法中使用它,是否有更简洁的方法来获取不变的引用?
这应该是不必要的; 你应该直接调用updateIndicators()
。
即:
public void run() { updateIndicators(); }
无需receiver
参考。 这为我编译。
UpdateIndicatorsReceiver.this.updateIndicators();