gpt4 book ai didi

java - 安卓 : How to get callback from custom method?

转载 作者:行者123 更新时间:2023-12-01 22:03:37 25 4
gpt4 key购买 nike

我有以下类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com