Timer with callback

Info

  • I have a class SensorClass that manages some sensors.
  • I have an interface with method A().
  • I have a tester 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);
    }
    
    链接地址: http://www.djcxy.com/p/74936.html

    上一篇: Android PagerAdapter destroyItem(),在使用片段时缓存一段时间

    下一篇: 定时器与回调