作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下类(class):
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;
}
}
我可以使用以下方法从 Controller 获取实例:
mTimerTaskHelper = TimerTaskHelper.getInstance(container);
但我想在每个之后在 Controller 中获得回调
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
和
public void stopExecution() {
handler.removeCallbacks(runnableInstance);
instance = null;
}
来自 Controller 。
请问我怎样才能以最好的方式做到这一点?
最佳答案
我想你想要这样的东西。
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
}});
关于java - 安卓 : How to get callback from custom method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33234696/
我是一名优秀的程序员,十分优秀!