2015-10-20 46 views
0

我有以下類:Android:如何從自定義方法獲取回調?

public class TimerTaskHelper { 

    private static TimerTaskHelper instance = null; 
    private static Integer ONE_MINUTE = 60000; 
    private static Handler handler; 
    private static Runnable runnableInstance; 
    private static Container container; 

    public static TimerTaskHelper getInstance(Container c) { 
     if (instance == null) { 
      instance = new TimerTaskHelper(c); 
     } 
     return instance; 
    } 

    public TimerTaskHelper(Container c) { 
     this.handler = new Handler(); 
     this.runnableInstance = runnableCode; 
     this.container = c; 
     // Kick off the first runnableInstance task right away 
     handler.post(runnableCode); 
    } 

    // Define the task to be run here 
    private Runnable runnableCode = new Runnable() { 
     @Override 
     public void run() { 
      // Do something here on the main thread 
      Logger.d("Called"); 
      // Repeat this runnableInstance code again every 2 seconds 
      handler.postDelayed(runnableCode, 2000); 
      container.notifyObservers(); 
     } 
    }; 

    public void stopExecution() { 
     handler.removeCallbacks(runnableInstance); 
     instance = null; 
    } 

} 

我能夠從控制器獲得實例使用:

mTimerTaskHelper = TimerTaskHelper.getInstance(container); 

,但我想每個

private Runnable runnableCode = new Runnable() { 
     @Override 
     public void run() { 
後得到回調控制器

and

public void stopExecution() { 
     handler.removeCallbacks(runnableInstance); 
     instance = null; 
    } 

來自控制器。

我該如何以最好的方式做到這一點?

+0

第一件事:什麼是使你的屬性...靜態?! – GhostCat

回答

3

我想你想要這樣的事情。

interface CallBack { 
void callBackMethod(); 
} 

public class TimerTaskHelper { 

private static TimerTaskHelper instance = null; 
private static Integer ONE_MINUTE = 60000; 
private static Handler handler; 
private static Runnable runnableInstance; 
private static Container container; 
private CallBack callback; 
public void setCallBack(CallBack cb){ 
callback=cb; 
} 
public static TimerTaskHelper getInstance(Container c) { 
    if (instance == null) { 
     instance = new TimerTaskHelper(c); 
    } 
    return instance; 
} 

public TimerTaskHelper(Container c) { 
    this.handler = new Handler(); 
    this.runnableInstance = runnableCode; 
    this.container = c; 
    // Kick off the first runnableInstance task right away 
    handler.post(runnableCode); 
} 

// Define the task to be run here 
private Runnable runnableCode = new Runnable() { 
    @Override 
    public void run() { 
     // Do something here on the main thread 
     Logger.d("Called"); 
     // Repeat this runnableInstance code again every 2 seconds 
     handler.postDelayed(runnableCode, 2000); 
     container.notifyObservers(); 
     if(callback!=null){ 
      callback.callBackMethod(); 
    } 
}; 
    mTimerTaskHelper = TimerTaskHelper.getInstance(container); 
    mTimerTaskHelper.setCallBack(new CallBack(){ 
    void callBackMethod(){ 
    //TODO your code 
    }}); 
相關問題