如何在 Android 停止消费广播?

How to stop spending broadcast in Android?

我有一个 Android 项目,它每秒发送一次广播,我想弄清楚如何在单击后停止它。

我的广播码是:

Intent broadcastIntent = new Intent ("send broadcast");
sendBroadcast(broadcastIntent);
stoptimertask(); //it is stopping broadcast for a second.

您可以定义两种方法:一种启动 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;
            }
        }
    });

最佳