开发者

Timer with callback

Info

  • I have a class SensorClass that manages some sensors.
  • I have an interface with method A().
  • I have a test开发者_C百科er class TestClass that implements the interface with method A() and passes this implementation to SensorClass. TestClass extends Activity.

Objective

  • Every X seconds I need to call the implemented method of the interface stored in SensorClass. It's a callback.
  • I don't know how is implemented method A(), so it can modify views of its activy.
  • I need a Timer because I want to start the callback -executing method A() from the stored interface in SensorClass- every X seconds. Thus, I do the following:
public void do (){
 timer.scheduleAtFixedRate (new TimerTask (){
  public void run (){
   storedInterface.A ();
  }
 }, 0, speed);
}
  • But as I said I don't know how is implemented A(). I have to run the method within runOnUIThread() because it can modify views.
private void startCallback (){
 runOnUiThread (new Runnable (){
  public void run (){
   storedInterface.A ();
  }
 });
}

public void do (){
 timer.scheduleAtFixedRate (new TimerTask (){
  public void run (){
   startCallback ();
  }
 }, 0, speed);
}
  • Problem: SensorClass is not an Activity, so runOnUIThread() will cause an error.

Posible workaround

Extend SensorClass from an Activity but SensorClass is not an Activity with methods onCreate(), onPause(), etc!!! I don't like this solution.

My question is: How can I call runOnUIThread() within a class that only recieves a context from an Activity? Or... Is there any other solution for my problem?

Thanks.


Solved using handler. Great tool!

public void do (){
    final Handler handler = new Handler ();
    timer.scheduleAtFixedRate (new TimerTask (){
        public void run (){
            handler.post (new Runnable (){
                public void run (){
                    storedInterface.A ();
                }
            });
        }
    }, 0, speed);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜