//indicate whether or not the loop is running
private boolean isRunning = false;
//used for handler to send empty msg
private final static int MSG_LOOP = 1;
private final static long LOOP_INTERVAL = 5000;
然后创建一个 Handler 示例来处理循环逻辑:
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_LOOP:
doStuff();
break;
}
}
};
private void doStuff() {
//after what you want to do is done, send another MSG_LOOP msg with delay
handler.sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
}
最后:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRunning) {
//cancel if any in the message queue
handler.removeMessages(MSG_LOOP);
} else {
//if you do not want to start the loop immediately, then use: "sendEmptyMessageDelayed"
handler.sendEmptyMessage(MSG_LOOP);
}
}
});
2条答案
按热度按时间gab6jxml1#
是的,举个简单的例子。
首先,创建两个常量值和一个示例变量:
然后创建一个
Handler
示例来处理循环逻辑:最后:
vof42yt12#
我会这样做的