我有一个Android项目,该项目每秒发送一次广播,并试图找出如何在单击后停止广播。
我的广播代码是:
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
stoptimertask(); //it is stopping broadcast for a second.
答案 0 :(得分:0)
您可以定义两种方法:一种启动Timer以每秒发送广播的方法,另一种则停止计时器的方法。
Timer timer;
private void startBroadcastLoop() {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// Send broadcast
Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
}
},0,1000); // Send broadcast every second
}
private void stopBroadcastLoop() {
if(timer!=null){
timer.cancel();
timer = null;
}
}
然后在按钮上,根据布尔值的状态调用正确的函数:
sendBroadcastBool = false;
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// If broadcast not sent yet
if (!sendBroadcastBool) {
startBroadcastLoop();
sendBroadcastBool = true;
}
else {
stopBroadcastLoop();
sendBroadcastBool = false;
}
}
});
最佳