[英]Android, how can i use callback from hellper method in controller?
[英]Android : How to get callback from custom method?
我有以下课程:
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() {
和
public void stopExecution() {
handler.removeCallbacks(runnableInstance);
instance = null;
}
从控制器。
请问如何才能最好地做到这一点?
我想你想要这样的事情。
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
}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.